package com.eco.fanliapp.service.impl;

import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.*;
import com.eco.fanliapp.dataoke.DaTaoKeItemInfoService;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.jd.JDSearchController;
import com.eco.fanliapp.pinduoduo.PDDSearchController;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.*;
import com.eco.fanliapp.vo.HaoDanKuSearchInfo.DataBean;
import com.eco.fanliapp.vo.TbkItemInfoGetInfo.NTbkItem;
import com.eco.fanliapp.vo.TbkPrivilegeGetInfo.TbkPrivilege;
import com.eco.fanliapp.vo.respone.DTKResponse;
import com.eco.fanliapp.vo.respone.ResponeOrderResults;
import com.eco.fanliapp.vo.respone.ResponeOrderResults.OrderDataBean;
import com.eco.fanliapp.vo.respone.ResponeResults;
import com.taobao.api.response.TbkDgOptimusMaterialResponse.MapData;
import jd.union.open.goods.query.response.*;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;


@Service
public class TaoBaoMethodServiceImpl implements ITaoBaoMethodService {

    private static final Logger log = LoggerFactory.getLogger(TaoBaoMethodServiceImpl.class);

    @Autowired
    private IAppOrderDetailService appOrderDetailService;
    @Autowired
    private IAppUserOrderService appUserOrderService;
    @Lazy
    @Autowired
    private IAppGoodsService appGoodsService;
    @Autowired
    private IAppGoodsShopdrsService appGoodsShopdrsService;
    @Autowired
    private ISyChannelGoodsService syChannelGoodsService;
    @Autowired
    private GoodsFreeMapper goodsFreeMapper;
    @Autowired
    private ICommissionFreezeService commissionFreezeService;
    @Autowired
    private FindItemIdUtils taoBaoUtils;
    @Autowired
    private IAppGeneralfeeschemeService appGeneralfeeschemeService;

    @Autowired
    private ITaoBaoService taoBaoService;

    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private IAppCompanyService appCompanyService;

    @Autowired
    private AppUserOrderMapper appUserOrderMapper;
    @Autowired
    private DaTaoKeItemInfoService daTaoKeItemInfoService;
    @Autowired
    private JDSearchController jdSearchController;
    @Autowired
    private PDDSearchController pddSearchController;

    /**
     * 弹窗返回结果-查询单个商品
     *
     * @param str
     * @param userId
     * @param channelUserId
     * @return
     */
    @Override
    public ResponeResults ItemMethon(String str, Long userId, String channelUserId) {
        // TODO Auto-generated method ItemMethon
        ServerResponse<List<NTbkItem>> response = taoBaoService.getSearchItemIdDetail(str);

        AppUser user = appUserService.selectAppUserByUserId(userId, 1);
        AppCompany appCompany = appCompanyService.findtAppCompany(user == null ? null : user.getCompanyId(), 1);

        //杀熟分佣
        AppOrderFeeScheme orderFeeScheme = null;//appCompany.getOrderFeeScheme();
        //普通分佣
        AppGeneralFeeScheme generalFeeScheme = appCompany.getGeneralFeeScheme();

        List<SyChannelGoods> syChannelGoodsAll = syChannelGoodsService.getAllAppChannelGoods(1);
        String fixedCommissionType = null;
        if (syChannelGoodsAll != null) {
            for (SyChannelGoods syChannelGoods : syChannelGoodsAll) {
                if (syChannelGoods.getItemId().toString().equals(str)) {
                    fixedCommissionType = syChannelGoods.getFixedCommissionType();
                    log.info("ItemMethon渠道下的商品   fixedCommissionType=" + fixedCommissionType);
                }
            }
        }

        if (response.getData() != null) {
            ResponeResults results = new ResponeResults();
            List<ResponeResults.DataBean> beans = new ArrayList<>();
            ResponeResults.DataBean bean = new ResponeResults.DataBean();
            for (NTbkItem item : response.getData()) {
                //调用的是高佣的接口实时转链计算的佣金
                ServerResponse<TbkPrivilege> response2 = taoBaoService.getPrivilegeItemId(Long.valueOf(item.getNumIid()), userId, null);

                HaoDanKuItemInfo info = taoBaoUtils.getHaoDanKuItemId(item.getNumIid().toString());
                if (info != null && info.getCode() == 1 && info.getData() != null) {
                    AppGoods goods = HDKUtils.getAppGoodsFromHDK(info.getData());
                    if (goods != null) {
                        bean.setVideoid(bean.getVideoid());
                    }
                }
                if (response2 != null && response2.isSuccess()) {
                    bean.setItemId(item.getNumIid().toString());
                    bean.setItempictUrl(item.getPictUrl());
                    if (bean.getItempictUrl() != null) {
//                        bean.setItempictUrl(bean.getItempictUrl().replaceAll(".jpg", ".jpg_200x200.jpg"));
                    }
                    bean.setItemPrice(item.getZkFinalPrice());
                    bean.setItemTitle(item.getTitle());
                    bean.setItemShortTitle(item.getTitle());
                    bean.setItemType(item.getUserType() == 1 ? "B" : "C");
                    //获取商品图片列表
                    if (item.getSmallImages() == null ||
                            item.getSmallImages().size() < 0) {
                        bean.setItemSmallImages(item.getPictUrl());
//                        bean.setItemSmallImagesFirst(item.getPictUrl() == null ? item.getPictUrl() : item.getPictUrl().replaceAll(".jpg", ".jpg_200x200.jpg"));
                        bean.setItemSmallImagesFirst(item.getPictUrl() == null ? item.getPictUrl() : item.getPictUrl());
                    } else {
                        bean.setItemSmallImages(item.getSmallImages().toString().replace("[", "").
                                replace("]", "").replace(" ", ""));
                        if (bean.getItemSmallImages() != null && bean.getItemSmallImages().split(",").length > 0) {
//                            bean.setItemSmallImagesFirst(bean.getItemSmallImages().split(",")[0].replaceAll(".jpg", ".jpg_200x200.jpg"));
                            bean.setItemSmallImagesFirst(bean.getItemSmallImages().split(",")[0]);
                        }

                    }
                    bean.setItemSale(item.getVolume().toString());
                    bean.setCouponUrl(response2.getData().getCouponInfo() == null ? response2.getData().getItemUrl() : response2.getData().getCouponClickUrl());
                    Integer coupon = response2.getData().getCouponInfo() == null ? 0 : NumberUtils.toInt(response2.getData().getCouponInfo());
                    bean.setCouponMoney(coupon);
                    String couponStartTime = response2.getData().getCouponStartTime();
                    String couponEndTime = response2.getData().getCouponEndTime();

                    bean.setCouponStartTime(couponStartTime == null ? String.valueOf(System.currentTimeMillis()) : DateFormatUtils.dateToStamp(couponStartTime));
                    bean.setCouponEndTime(couponEndTime == null ? String.valueOf(System.currentTimeMillis() + 86400000) : DateFormatUtils.dateToStamp(couponEndTime));

                    bean.setFreeShipment(true);
                    bean.setHasCoupon(response2.getData().getCouponInfo() == null ? false : true);
                    bean.setShopName(item.getNick());
                    //佣金和返后价计算规则
                    //券后价  = 原价 - 优惠券金额
                    //返利金额 = 券后价 * 佣金比例（佣金比例是%要除100）
                    //返后价 = 原价 - 返利金额
                    //到手价 = 原价 - 返利金额- （新修改）返利金额
                    //节省价格 = 券价+返利
                    Integer s = ApiEnum.YOUKEMODE;//游客模式的佣金

                    BigDecimal itemendprice = BigDecimalUtils.Format(
                            new BigDecimal(item.getZkFinalPrice() == null ? "0" : item.getZkFinalPrice())
                                    .subtract(new BigDecimal(coupon))
                    );
                    s = getCommissionRate(appCompany, orderFeeScheme, generalFeeScheme, userId,
                            BigDecimalUtils.FanliMoney(response2.getData().getMaxCommissionRate(),
                                    itemendprice).doubleValue());
                    if (fixedCommissionType == null) {
                        BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(),
                                BigDecimalUtils.FanliMoney(response2.getData().getMaxCommissionRate(),
                                        itemendprice));
                        BigDecimal flh = itemendprice;
                        bean.setFanliMoney(fl);
                        bean.setFanlihoMoney(flh);
                        bean.setTheirPriceMoney(flh.subtract(fl));
                        bean.setSpareMoney(fl.add(new BigDecimal(coupon)));

//                        BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(), BigDecimalUtils.Format(info.getData().getTkmoney()));
//                        BigDecimal flh = BigDecimalUtils.Format(Double.valueOf(info.getData().getItemendprice()));
//                        bean.setFanliMoney(fl);
//                        bean.setFanlihoMoney(flh);
//                        bean.setTheirPriceMoney(flh.subtract(fl));
                    } else {
                        BigDecimal flh = BigDecimalUtils.Format(itemendprice);
                        bean.setFanliMoney(new BigDecimal(fixedCommissionType));
                        bean.setFanlihoMoney(flh);
                        bean.setTheirPriceMoney(flh.subtract(new BigDecimal(fixedCommissionType)));
                        bean.setSpareMoney(new BigDecimal(fixedCommissionType).add(new BigDecimal(coupon)));
                    }
                    beans.add(bean);
                }
            }
            results.setData(beans);
            return results;
        } else {
            return null;
        }
    }

    /**
     * 1好单库，2，大淘客，3联盟
     *
     * @param itemId
     * @param userId
     * @param channelUserId
     * @return
     */
    @Override
    public ResponeResults ItemPopupMethon(String itemId, Long userId, String channelUserId) {


        AppUser user = appUserService.selectAppUserByUserId(userId, 1);
        AppCompany appCompany = appCompanyService.findtAppCompany(user == null ? null : user.getCompanyId(), 1);
        //杀熟分佣
        AppOrderFeeScheme orderFeeScheme = null;
        //普通分佣
        AppGeneralFeeScheme generalFeeScheme = appCompany.getGeneralFeeScheme();

        List<SyChannelGoods> syChannelGoodsAll = syChannelGoodsService.getAllAppChannelGoods(1);
        String fixedCommissionType = null;
        if (syChannelGoodsAll != null) {
            for (SyChannelGoods syChannelGoods : syChannelGoodsAll) {
                if (syChannelGoods.getItemId().toString().equals(itemId)) {
                    fixedCommissionType = syChannelGoods.getFixedCommissionType();
                    log.info("ItemMethon渠道下的商品   fixedCommissionType=" + fixedCommissionType);
                }
            }
        }

        ResponeResults results = new ResponeResults();
        List<ResponeResults.DataBean> beans = new ArrayList<>();
        ResponeResults.DataBean bean = new ResponeResults.DataBean();
        //先查好单库
        HaoDanKuItemInfo hdkRespones = taoBaoUtils.getHaoDanKuItemId(itemId);
        //高拥，联盟
        ServerResponse<TbkPrivilege> tbkResponse = taoBaoService.getPrivilegeItemId(Long.valueOf(itemId), userId, null);
        //大淘客
        DTKResponse dtkResponse = null;
        Integer type = 1;//默认为1好单库

        if (hdkRespones != null && hdkRespones.getCode() == 1 && hdkRespones.getData() != null) {
            //联盟
            if (tbkResponse != null && tbkResponse.getData() != null && tbkResponse.isSuccess()) {
                BigDecimal rate_one = new BigDecimal(hdkRespones.getData().getTkrates()).subtract(new BigDecimal("100"));
                BigDecimal rate_two = new BigDecimal(tbkResponse.getData().getMaxCommissionRate()).subtract(new BigDecimal("100"));
                if (rate_one.compareTo(rate_two) == 0) {
                    type = 1;//走好单库
                } else {
                    type = 2;//大淘客，联盟
                }
            }
        } else {
            type = 2;
        }
        if (type != 1) {
            dtkResponse = daTaoKeItemInfoService.itemInfoByItemId(itemId);
            if (tbkResponse != null && tbkResponse.getData() != null && tbkResponse.isSuccess()) {
                BigDecimal rate_one = new BigDecimal(dtkResponse.getData().getCommissionRate()).subtract(new BigDecimal("100"));
                BigDecimal rate_two = new BigDecimal(tbkResponse.getData().getMaxCommissionRate()).subtract(new BigDecimal("100"));
                if (rate_one.compareTo(rate_two) == 0) {
                    type = 2;//大淘客
                } else {
                    type = 3;//联盟
                }
            } else {
                type = 3;//联盟
            }
        }
        if (type == 1) {
            bean.setActivityId(hdkRespones.getData().getActivityid());
            bean.setVideoid(hdkRespones.getData().getVideoid());
            bean.setItemId(hdkRespones.getData().getItemid());
            bean.setItempictUrl(hdkRespones.getData().getItempic());
            bean.setItemPrice(hdkRespones.getData().getItemprice());
            bean.setItemTitle(hdkRespones.getData().getItemtitle());
            bean.setItemShortTitle(hdkRespones.getData().getItemshorttitle());
            bean.setItemType(hdkRespones.getData().getShoptype());
            //获取商品图片列表
            bean.setItemSmallImages(hdkRespones.getData().getTaobao_image());
            if (hdkRespones.getData().getTaobao_image() != null && hdkRespones.getData().getTaobao_image().split(",").length > 0) {
                bean.setItemSmallImagesFirst(hdkRespones.getData().getTaobao_image().split(",")[0]);
            }

            bean.setItemSale(hdkRespones.getData().getItemsale());
            bean.setCouponUrl(hdkRespones.getData().getCouponurl());
            Integer coupon = hdkRespones.getData().getCouponmoney() == null ? 0 : NumberUtils.toInt(hdkRespones.getData().getCouponmoney());
            bean.setCouponMoney(coupon);
            String couponStartTime = hdkRespones.getData().getCouponstarttime();
            String couponEndTime = hdkRespones.getData().getCouponendtime();
            bean.setCouponStartTime(couponStartTime == null ? String.valueOf(System.currentTimeMillis()) : couponStartTime + "000");
            bean.setCouponEndTime(couponEndTime == null ? String.valueOf(System.currentTimeMillis() + 86400000) : couponEndTime + "000");
            bean.setFreeShipment(true);
            bean.setHasCoupon(coupon > 0 ? true : false);
            bean.setShopName(hdkRespones.getData().getShopname());
            //佣金和返后价计算规则
            //券后价  = 原价 - 优惠券金额
            //返利金额 = 券后价 * 佣金比例（佣金比例是%要除100）
            //返后价 = 原价 - 返利金额
            //到手价 = 原价 - 返利金额- （新修改）返利金额
            //节省价格 = 券价+返利
            Integer s = ApiEnum.YOUKEMODE;//游客模式的佣金
            BigDecimal itemendprice = new BigDecimal(hdkRespones.getData().getItemendprice());
            s = getCommissionRate(appCompany, orderFeeScheme, generalFeeScheme, userId,
                    BigDecimalUtils.FanliMoney(hdkRespones.getData().getTkrates(),
                            itemendprice).doubleValue());
            if (fixedCommissionType == null) {
                BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(),
                        BigDecimalUtils.FanliMoneyScale(hdkRespones.getData().getTkrates(),
                                itemendprice));
                BigDecimal flh = itemendprice;
                bean.setFanliMoney(fl);
                bean.setFanlihoMoney(flh);
                bean.setTheirPriceMoney(flh.subtract(fl));
                bean.setSpareMoney(fl.add(new BigDecimal(coupon)));
            } else {
                BigDecimal flh = BigDecimalUtils.Format(itemendprice);
                bean.setFanliMoney(new BigDecimal(fixedCommissionType));
                bean.setFanlihoMoney(flh);
                bean.setTheirPriceMoney(flh.subtract(new BigDecimal(fixedCommissionType)));
                bean.setSpareMoney(new BigDecimal(fixedCommissionType).add(new BigDecimal(coupon)));
            }
            beans.add(bean);
        } else if (type == 2) {
            //2查询大淘客
            //3查询联盟
            ServerResponse<List<NTbkItem>> response = taoBaoService.getSearchItemIdDetail(itemId);
            if (dtkResponse != null && dtkResponse.getCode() == 0 && dtkResponse.getData() != null) {
                bean.setItemId(dtkResponse.getData().getGoodsId());
                String mainPic = dtkResponse.getData().getMainPic();
                bean.setItempictUrl(mainPic.startsWith("https") ? mainPic : "https:" + mainPic);
                bean.setItemPrice(dtkResponse.getData().getOriginalPrice());
                bean.setItemTitle(dtkResponse.getData().getTitle());
                bean.setItemShortTitle(dtkResponse.getData().getDtitle());
                bean.setItemType(dtkResponse.getData().getShopType() == "1" ? "B" : "C");
                if (response != null && response.isSuccess() && response.getData().size() == 1) {
                    bean.setItemSmallImages(response.getData().get(0).getSmallImages().toString().replace("[", "").
                            replace("]", "").replace(" ", ""));
                    if (bean.getItemSmallImages() != null && bean.getItemSmallImages().split(",").length > 0) {
                        bean.setItemSmallImagesFirst(bean.getItemSmallImages().split(",")[0]);
                    }

                }
                bean.setItemSale(dtkResponse.getData().getMonthSales());
                bean.setCouponUrl(dtkResponse.getData().getCouponLink());
                Integer coupon = dtkResponse.getData().getCouponPrice() == null ? 0 : NumberUtils.toInt(dtkResponse.getData().getCouponPrice());
                bean.setCouponMoney(coupon);
                String couponStartTime = dtkResponse.getData().getCouponStartTime();
                String couponEndTime = dtkResponse.getData().getCouponEndTime();
                bean.setCouponStartTime(couponStartTime == null ? String.valueOf(System.currentTimeMillis()) : DateFormatUtils.dateToStamp(couponStartTime));
                bean.setCouponEndTime(couponEndTime == null ? String.valueOf(System.currentTimeMillis() + 86400000) : DateFormatUtils.dateToStamp(couponEndTime));
                bean.setFreeShipment(true);
                bean.setHasCoupon(coupon > 0 ? true : false);
                bean.setShopName(dtkResponse.getData().getShopName());
                //佣金和返后价计算规则
                //券后价  = 原价 - 优惠券金额
                //返利金额 = 券后价 * 佣金比例（佣金比例是%要除100）
                //返后价 = 原价 - 返利金额
                //到手价 = 原价 - 返利金额- （新修改）返利金额
                //节省价格 = 券价+返利
                Integer s = ApiEnum.YOUKEMODE;//游客模式的佣金
                BigDecimal itemendprice = null;
                if (Double.valueOf(dtkResponse.getData().getActualPrice()) == Double.valueOf(bean.getItemPrice()) - Double.valueOf(coupon)) {
                    itemendprice = new BigDecimal(dtkResponse.getData().getActualPrice());
                } else {
                    itemendprice = new BigDecimal((Double.valueOf(bean.getItemPrice()) - Double.valueOf(coupon)) > Double.valueOf(dtkResponse.getData().getActualPrice()) ? String.valueOf(Double.valueOf(dtkResponse.getData().getActualPrice()) - coupon) : dtkResponse.getData().getActualPrice());
                }
                s = getCommissionRate(appCompany, orderFeeScheme, generalFeeScheme, userId,
                        BigDecimalUtils.FanliMoney(dtkResponse.getData().getCommissionRate(),
                                itemendprice).doubleValue());
                if (fixedCommissionType == null) {
                    BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(),
                            BigDecimalUtils.FanliMoneyScale(dtkResponse.getData().getCommissionRate(),
                                    itemendprice));
                    BigDecimal flh = itemendprice;
                    bean.setFanliMoney(fl);
                    bean.setFanlihoMoney(flh);
                    bean.setTheirPriceMoney(flh.subtract(fl));
                    bean.setSpareMoney(fl.add(new BigDecimal(coupon)));
                } else {
                    BigDecimal flh = BigDecimalUtils.Format(itemendprice);
                    bean.setFanliMoney(new BigDecimal(fixedCommissionType));
                    bean.setFanlihoMoney(flh);
                    bean.setTheirPriceMoney(flh.subtract(new BigDecimal(fixedCommissionType)));
                    bean.setSpareMoney(new BigDecimal(fixedCommissionType).add(new BigDecimal(coupon)));
                }
                beans.add(bean);

            }
        } else if (type == 3) {
            //联盟
            ServerResponse<List<NTbkItem>> response = taoBaoService.getSearchItemIdDetail(itemId);
            if (response != null && response.isSuccess() && response.getData().size() == 1) {
                NTbkItem item = response.getData().get(0);
                //调用的是高佣的接口实时转链计算的佣金
                if (tbkResponse != null && tbkResponse.isSuccess()) {
                    bean.setItemId(item.getNumIid().toString());
                    bean.setItempictUrl(item.getPictUrl());
                    bean.setItemPrice(item.getZkFinalPrice());
                    bean.setItemTitle(item.getTitle());
                    bean.setItemShortTitle(item.getTitle());
                    bean.setItemType(item.getUserType() == 1 ? "B" : "C");
                    //获取商品图片列表
                    if (item.getSmallImages() == null ||
                            item.getSmallImages().size() < 0) {
                        bean.setItemSmallImages(item.getPictUrl());
                        bean.setItemSmallImagesFirst(item.getPictUrl() == null ? item.getPictUrl() : item.getPictUrl());
                    } else {
                        bean.setItemSmallImages(item.getSmallImages().toString().replace("[", "").
                                replace("]", "").replace(" ", ""));
                        if (bean.getItemSmallImages() != null && bean.getItemSmallImages().split(",").length > 0) {
                            bean.setItemSmallImagesFirst(bean.getItemSmallImages().split(",")[0]);
                        }

                    }
                    bean.setItemSale(item.getVolume().toString());
                    bean.setCouponUrl(tbkResponse.getData().getCouponInfo() == null ? tbkResponse.getData().getItemUrl() : tbkResponse.getData().getCouponClickUrl());
                    Integer coupon = tbkResponse.getData().getCouponInfo() == null ? 0 : NumberUtils.toInt(tbkResponse.getData().getCouponInfo());
                    bean.setCouponMoney(coupon);
                    String couponStartTime = tbkResponse.getData().getCouponStartTime();
                    String couponEndTime = tbkResponse.getData().getCouponEndTime();

                    bean.setCouponStartTime(couponStartTime == null ? String.valueOf(System.currentTimeMillis()) : DateFormatUtils.dateToStamp(couponStartTime));
                    bean.setCouponEndTime(couponEndTime == null ? String.valueOf(System.currentTimeMillis() + 86400000) : DateFormatUtils.dateToStamp(couponEndTime));

                    bean.setFreeShipment(true);
                    bean.setHasCoupon(tbkResponse.getData().getCouponInfo() == null ? false : true);
                    bean.setShopName(item.getNick());
                    //佣金和返后价计算规则
                    //券后价  = 原价 - 优惠券金额
                    //返利金额 = 券后价 * 佣金比例（佣金比例是%要除10000）
                    //返后价 = 原价 - 返利金额
                    //到手价 = 原价 - 返利金额- （新修改）返利金额
                    //节省价格 = 券价+返利
                    Integer s = ApiEnum.YOUKEMODE;//游客模式的佣金
                    BigDecimal itemendprice = BigDecimalUtils.Format(
                            new BigDecimal(item.getZkFinalPrice() == null ? "0" : item.getZkFinalPrice())
                                    .subtract(new BigDecimal(coupon))
                    );
                    s = getCommissionRate(appCompany, orderFeeScheme, generalFeeScheme, userId,
                            BigDecimalUtils.FanliMoney(tbkResponse.getData().getMaxCommissionRate(),
                                    itemendprice).doubleValue());
                    if (fixedCommissionType == null) {
                        BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(),
                                BigDecimalUtils.FanliMoneyScale(tbkResponse.getData().getMaxCommissionRate(),
                                        itemendprice));
                        BigDecimal flh = itemendprice;
                        bean.setFanliMoney(fl);
                        bean.setFanlihoMoney(flh);
                        bean.setTheirPriceMoney(flh.subtract(fl));
                        bean.setSpareMoney(fl.add(new BigDecimal(coupon)));
                    } else {
                        BigDecimal flh = BigDecimalUtils.Format(itemendprice);
                        bean.setFanliMoney(new BigDecimal(fixedCommissionType));
                        bean.setFanlihoMoney(flh);
                        bean.setTheirPriceMoney(flh.subtract(new BigDecimal(fixedCommissionType)));
                        bean.setSpareMoney(new BigDecimal(fixedCommissionType).add(new BigDecimal(coupon)));
                    }
                    beans.add(bean);
                }
            }
        }
        if (beans != null && beans.size() > 0) {
            results.setData(beans);
            return results;
        }
        return null;
    }

    /**
     * 好单库通用封转结果-未启用
     *
     * @param info
     * @param userId
     * @return
     */
    @Override
    public ResponeResults ItemMethon2(HaoDanKuSearchInfo info, Long userId) {

        AppUser user = appUserService.selectAppUserByUserId(userId, 1);
        AppCompany appCompany = appCompanyService.findtAppCompany(user == null ? null : user.getCompanyId(), 1);

        //杀熟分佣
        AppOrderFeeScheme orderFeeScheme = appCompany.getOrderFeeScheme();
        //普通分佣
        AppGeneralFeeScheme generalFeeScheme = appCompany.getGeneralFeeScheme();

        // TODO Auto-generated method stub
        if (info.getData() != null) {
            ResponeResults results = new ResponeResults();
            results.setMin_id(info.getMin_id());
            List<ResponeResults.DataBean> beans = new ArrayList<ResponeResults.DataBean>();
            for (DataBean dataBean : info.getData()) {
                ResponeResults.DataBean bean = new ResponeResults.DataBean();
                bean.setItemId(dataBean.getItemid());
                bean.setItemTitle(dataBean.getItemtitle());
                bean.setItemShortTitle(dataBean.getItemshorttitle());
                bean.setItemPrice(dataBean.getItemprice());
                bean.setItempictUrl(dataBean.getItempic());
                if (bean.getItempictUrl() != null) {
//                    bean.setItempictUrl(bean.getItempictUrl().replaceAll(".jpg", ".jpg_200x200.jpg"));
                }
                bean.setItemSmallImages(dataBean.getTaobao_image() == null ? dataBean.getTaobao_image() : dataBean.getTaobao_image().replace(" ", ""));
                bean.setCouponUrl(dataBean.getCouponurl());
                bean.setCouponStartTime(dataBean.getCouponstarttime() + "000");
                bean.setCouponEndTime(dataBean.getCouponendtime() + "000");
                bean.setFreeShipment(true);
                bean.setItemType(dataBean.getShoptype());
                bean.setItemSale(dataBean.getItemsale());
                bean.setCouponMoney(NumberUtils.toInt(dataBean.getCouponmoney()));
                bean.setHasCoupon(dataBean.getCouponmoney() == null ? false : true);
                bean.setShopName(dataBean.getShopname());
                bean.setShopId(dataBean.getShopid());

                Integer s = ApiEnum.YOUKEMODE;//游客模式的佣金
                s = getCommissionRate(appCompany, orderFeeScheme, generalFeeScheme, userId, Double.valueOf(dataBean.getTkmoney()));
                BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(), BigDecimalUtils.Format(dataBean.getTkmoney()));
                BigDecimal flh = BigDecimalUtils.Format(dataBean.getItemendprice());
                bean.setFanliMoney(fl);
                bean.setFanlihoMoney(flh);
                bean.setTheirPriceMoney(flh.subtract(fl));
                beans.add(bean);
            }
            results.setData(beans);
            return results;
        } else {
            return null;
        }
    }

    /**
     * 好单单品详情返回结果
     *
     * @param info
     * @param userId
     * @param channelUserId
     * @param period
     * @return
     */
    @Override
    public ResponeResults ItemMethon3(HaoDanKuItemInfo info, Long userId, String channelUserId, String period, Integer isCollect) {
        // TODO Auto-generated method ItemMethon3
        ResponeResults results = new ResponeResults();
        List<ResponeResults.DataBean> beans = new ArrayList<>();
        ResponeResults.DataBean bean = new ResponeResults.DataBean();
        //调用的是高佣的接口实时转链计算的佣金
        ServerResponse<TbkPrivilege> response2 = taoBaoService.getPrivilegeItemId(Long.valueOf(info.getData().getItemid()), userId, null);
        List<SyChannelGoods> syChannelGoodsAll = syChannelGoodsService.getAllAppChannelGoods(1);
        if (response2 != null && response2.isSuccess()) {
            bean.setActivityId(info.getData().getActivityid());
            bean.setVideoid(info.getData().getVideoid());
            bean.setItemId(info.getData().getItemid());
            bean.setItemTitle(info.getData().getItemtitle());
            bean.setItemShortTitle(info.getData().getItemshorttitle());
            bean.setItemPrice(info.getData().getItemprice());
            bean.setItempictUrl(info.getData().getItempic());
            bean.setVideoid(info.getData().getVideoid());
            if (bean.getItempictUrl() != null) {
//                bean.setItempictUrl(bean.getItempictUrl().replaceAll(".jpg", ".jpg_200x200.jpg"));
            }
            bean.setItemSmallImages(info.getData().getTaobao_image() == null ? info.getData().getItempic() : info.getData().getTaobao_image().replace(" ", ""));
            if (bean.getItemSmallImages() != null && bean.getItemSmallImages().split(",").length > 0) {
//                bean.setItemSmallImagesFirst(bean.getItemSmallImages().split(",")[0].replaceAll(".jpg", ".jpg_200x200.jpg"));
                bean.setItemSmallImagesFirst(bean.getItemSmallImages().split(",")[0]);
            }

            Integer coupon = response2.getData().getCouponInfo() == null ? 0 : NumberUtils.toInt(response2.getData().getCouponInfo());
            if (coupon != 0) {
                bean.setCouponUrl(response2.getData().getCouponClickUrl() + "&activityId=" + info.getData().getActivityid());
                bean.setCouponStartTime(DateFormatUtils.dateToStamp(response2.getData().getCouponStartTime()));
                bean.setCouponEndTime(DateFormatUtils.dateToStamp(response2.getData().getCouponEndTime()));
                bean.setCouponMoney(coupon);
                bean.setHasCoupon(true);
            } else {
                bean.setCouponUrl(response2.getData().getItemUrl());
                bean.setCouponStartTime(String.valueOf(System.currentTimeMillis()));
                bean.setCouponEndTime(String.valueOf(System.currentTimeMillis() + 86400000));
                bean.setCouponMoney(coupon);
                bean.setHasCoupon(false);
            }
            bean.setFreeShipment(true);
            bean.setItemType(info.getData().getShoptype());
            bean.setItemSale(info.getData().getItemsale());
            bean.setShopId(info.getData().getShopid());
            bean.setShopName(info.getData().getShopname());
            AppGoodsShopdrs shopdrs = appGoodsShopdrsService.selectAppGoodsShopdrsByShopId(info.getData().getShopid());
            if (shopdrs != null) {
                WeiYiInfo info2 = JsonUtils.getJsonToBean(shopdrs.getWyItemDetail(), WeiYiInfo.class);
                if (info != null) {
                    bean.setShopPicUrl(info2.getData().getSeller().getShopIcon() == null ? "" : "https:" + info2.getData().getSeller().getShopIcon());
                    bean.setShopTag(info2.getData().getSeller().getTagIcon());
                    bean.setShopUrl(info2.getData().getSeller().getTaoShopUrl() == null ? "" : "https:" + info2.getData().getSeller().getTaoShopUrl());
                    bean.setItemDetail(info2.getData().getItem_detail());
                    bean.setEval(info2.getData().getSeller().getEvaluates());
                }
            } else {
                bean.setShopPicUrl(null);
                bean.setShopTag(null);
                bean.setShopUrl(null);
                bean.setItemDetail(null);
                bean.setEval(null);
            }

            AppUser user = appUserService.selectAppUserByUserId(userId, 1);
            AppCompany appCompany = appCompanyService.findtAppCompany(user == null ? null : user.getCompanyId(), 1);

            //杀熟分佣
            AppOrderFeeScheme orderFeeScheme = appCompany.getOrderFeeScheme();
            //普通分佣
            AppGeneralFeeScheme generalFeeScheme = appCompany.getGeneralFeeScheme();

            String fixedCommissionType = null;

            fixedCommissionType = getFixedCommission(info.getData().getItemid(), userId, fixedCommissionType, syChannelGoodsAll);

            Integer s = ApiEnum.YOUKEMODE;//游客模式

            s = getCommissionRate(appCompany, orderFeeScheme, generalFeeScheme, userId, Double.valueOf(info.getData().getTkmoney()));

            if ("1".equals(period)) {
                BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(), BigDecimalUtils.Format(info.getData().getTkmoney()));
                BigDecimal flh = BigDecimalUtils.Format(Double.valueOf(info.getData().getItemendprice()));
                bean.setFanliMoney(fl);
                bean.setFanlihoMoney(flh);
                bean.setTheirPriceMoney(flh.subtract(fl));
            } else {
                //查询免单商品
                GoodsFree free = goodsFreeMapper.selectByGoodsId(info.getData().getItemid());
                if (free != null) {
                    BigDecimal fl = BigDecimalUtils.Format(info.getData().getTkmoney());
                    BigDecimal flh = BigDecimal.valueOf(0);
                    bean.setFanliMoney(fl);
                    bean.setFanlihoMoney(flh);
                    bean.setTheirPriceMoney(flh.subtract(fl));
                } else {

                    if (fixedCommissionType == null) {
                        BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(), BigDecimalUtils.Format(info.getData().getTkmoney()));
                        BigDecimal flh = BigDecimalUtils.Format(Double.valueOf(info.getData().getItemendprice()));
                        bean.setFanliMoney(fl);
                        bean.setFanlihoMoney(flh);
                        bean.setTheirPriceMoney(flh.subtract(fl));
                    } else {
                        if (isCollect != null && isCollect == 1) {
                            BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(), BigDecimalUtils.Format(info.getData().getTkmoney()));
                            BigDecimal flh = BigDecimalUtils.Format(Double.valueOf(info.getData().getItemendprice()));
                            bean.setFanliMoney(fl);
                            bean.setFanlihoMoney(flh);
                            bean.setTheirPriceMoney(flh.subtract(fl));
                        } else {
                            BigDecimal flh = BigDecimalUtils.Format(Double.valueOf(info.getData().getItemendprice()));
                            bean.setFanliMoney(new BigDecimal(fixedCommissionType));
                            bean.setFanlihoMoney(flh);
                            bean.setTheirPriceMoney(flh.subtract(new BigDecimal(fixedCommissionType)));
                        }
                    }
                }
            }

            bean.setActivityType(info.getData().getActivity_type());
            bean.setStartTime(info.getData().getStart_time() == null ? "0" : info.getData().getStart_time() + "000");
            bean.setEndTime(info.getData().getEnd_time() == null ? "0" : info.getData().getEnd_time() + "000");
            beans.add(bean);
            results.setData(beans);
            return results;
        } else {
            if (response2.getStatus() == 601) {
                results.setMin_id(601);
                return results;
            }
            return null;
        }
    }

    /**
     * 超级搜索
     *
     * @param keyword
     * @param sort
     * @param pageSize
     * @param pageNo
     * @param userId
     * @param hasCoupon
     * @param issearchOne
     * @param channelUserId
     * @return
     */
    @Override
    public ResponeResults itemMethon4(String keyword,
                                      String sort, Long pageSize, Long pageNo, Long userId, Boolean hasCoupon, Boolean issearchOne, String
                                              channelUserId, String type) {
        // TODO Auto-generated method itemMethon4
//        ServerResponse<List<TbkScMaterialOptionalInfo.MapData>> responseFalse = null;
//        if (!issearchOne) {
//            if (CollectionUtils.isEmpty(response.getData())) {
//                response = taoBaoService.SearchSuperTitle(keyword, sort, pageSize, pageNo, userId, false);
//            } else {
//                if (response.getData().size() < pageSize) {
//                    responseFalse = taoBaoService.SearchSuperTitle(keyword, sort, pageSize, pageNo, userId, false);
//                    Set<String> itemIds = new HashSet<>();
//                    int i = response.getData().size();
//                    if (response.getData().size() > 0) {
//                        List<TbkScMaterialOptionalInfo.MapData> responseDatas = response.getData();
//                        for (TbkScMaterialOptionalInfo.MapData mapData : responseDatas) {
//                            itemIds.add(mapData.getItemId());
//                        }
//                    }
//                    if (responseFalse != null && responseFalse.getData() != null && responseFalse.getData().size() > 0) {
//                        List<TbkScMaterialOptionalInfo.MapData> responseFalseDatas = responseFalse.getData();
//                        for (TbkScMaterialOptionalInfo.MapData mapData : responseFalseDatas) {
//                            if (i >= pageSize) {
//                                break;
//                            }
//                            if (!itemIds.contains(mapData.getItemId())) {
//                                response.getData().add(mapData);
//                            }
//                        }
//                    }
//                }
//
//            }
//
////            if (CollectionUtils.isEmpty(response.getData())) {
////                response = taoBaoService.SearchSuperTitle(keyword, sort, pageSize, pageNo, userId, false);
////            }
//        }

//        if (!StringUtils.isEmpty(responseFalse) && !CollectionUtils.isEmpty(responseFalse.getData()))
//            response.getData().addAll(responseFalse.getData());


        AppUser user = appUserService.selectAppUserByUserId(userId, 1);
        AppCompany appCompany = appCompanyService.findtAppCompany(user == null ? null : user.getCompanyId(), 1);

        List<SyChannelGoods> syChannelGoodsAll = syChannelGoodsService.getAllAppChannelGoods(1);

        //杀熟分佣
        AppOrderFeeScheme orderFeeScheme = appCompany.getOrderFeeScheme();


        //1 淘宝 2京东  3拼多多
        if ("2".equals(type)) {
            //sort 综合默认
            UnionOpenGoodsQueryResponse response = jdSearchController.jdGoodsQuery(keyword, pageNo, pageSize, sort, hasCoupon);
            if (response != null && response.getData() != null) {
                ResponeResults results = new ResponeResults();
                List<ResponeResults.DataBean> beans = new ArrayList<ResponeResults.DataBean>();
                for (GoodsResp item : response.getData()) {
                    ResponeResults.DataBean bean = new ResponeResults.DataBean();
                    String fixedCommissionType = null;
                    if (syChannelGoodsAll != null) {
                        for (SyChannelGoods syChannelGoods : syChannelGoodsAll) {
                            if (syChannelGoods.getItemId().toString().equals(item.getSkuId())) {
                                fixedCommissionType = syChannelGoods.getFixedCommissionType();
                                log.info("ItemMethon渠道下的商品   fixedCommissionType=" + fixedCommissionType);
                            }
                        }
                    }

                    if ("g".equals(item.getOwner())) {
                        bean.setSaleType("Z");
                    }
                    bean.setItemType("J");

                    bean.setMaterialUrl(item.getMaterialUrl());
                    bean.setItemSale(item.getComments().toString());//评论数
//                    bean.setItemSale(item.getInOrderCount30Days().toString());//30天引单量
                    bean.setItemId(item.getSkuId().toString());
                    bean.setItemTitle(item.getSkuName());
                    bean.setShopName(item.getShopInfo().getShopName());
                    for (Coupon coupon : item.getCouponInfo().getCouponList()) {
                        bean.setCouponMoney(coupon.getDiscount() == null ? 0 : coupon.getDiscount().intValue());
                        bean.setCouponEndTime(coupon.getUseEndTime().toString());
                        bean.setCouponStartTime(coupon.getUseStartTime().toString());
                        bean.setCouponUrl(coupon.getLink());
                    }
                    if (bean.getCouponMoney() == null) {
                        bean.setCouponMoney(0);
                    }
                    bean.setItemPrice(item.getPriceInfo().getPrice().toString());

//                    for (UrlInfo urlInfo : item.getImageInfo().getImageList()) {
//
//                        if (urlInfo.getUrl() != null && urlInfo.getUrl().split(",").length > 0) {
//                            bean.setItemSmallImages(urlInfo.getUrl());
//                            bean.setItemSmallImagesFirst(urlInfo.getUrl().split(",")[0]);
//                            bean.setItempictUrl(urlInfo.getUrl().split(",")[0]);
//                        }
//                    }
                    UrlInfo[] urlInfo = item.getImageInfo().getImageList();
                    bean.setItempictUrl(urlInfo[0].getUrl());
                    String promotionRate = item.getCommissionInfo().getCommissionShare() == null ? "0" : item.getCommissionInfo().getCommissionShare() + "";//佣金比例

                    //普通分佣
                    AppGeneralFeeScheme generalFeeScheme = appCompany.getJdScheme();
                    BigDecimal itemendprice = BigDecimalUtils.Format(
                            new BigDecimal(bean.getItemPrice() == null ? "0" : bean.getItemPrice())
                                    .subtract(new BigDecimal(bean.getCouponMoney() == null ? 0 : bean.getCouponMoney()))
                    );
                    Integer s = getCommissionRate(appCompany, null, generalFeeScheme, userId == null ? 0 : userId,
                            BigDecimalUtils.FanliMoneyScale(promotionRate, itemendprice).doubleValue());

                    if (fixedCommissionType == null) {
                        BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(),
                                BigDecimalUtils.FanliMoneyScale(promotionRate, itemendprice));
                        bean.setFanliMoney(fl);
                        bean.setFanlihoMoney(itemendprice);
                        bean.setTheirPriceMoney(itemendprice.subtract(fl));

                    } else {
                        BigDecimal flh = BigDecimalUtils.Format(itemendprice);
                        bean.setFanliMoney(new BigDecimal(fixedCommissionType));
                        bean.setFanlihoMoney(flh);
                        bean.setTheirPriceMoney(flh.subtract(new BigDecimal(fixedCommissionType)));
                    }
                    beans.add(bean);
                }
                results.setData(beans);
                return results;
            }

        } else if ("3".equals(type)) {
            //sort 0综合 3价格升序 4价格降序 5销量升序 6销量降序
            PddGoodsSearchResponse response = pddSearchController.PddGoodsSearch(keyword, pageNo, pageSize, sort, hasCoupon);
            if (response != null && response.getGoods_list() != null) {
                ResponeResults results = new ResponeResults();
                List<ResponeResults.DataBean> beans = new ArrayList<ResponeResults.DataBean>();
                for (PddGoodsSearchResponse.GoodsList item : response.getGoods_list()) {
                    ResponeResults.DataBean bean = new ResponeResults.DataBean();
                    String fixedCommissionType = null;
                    if (syChannelGoodsAll != null) {
                        for (SyChannelGoods syChannelGoods : syChannelGoodsAll) {
                            if (syChannelGoods.getItemId().toString().equals(item.getGoods_id())) {
                                fixedCommissionType = syChannelGoods.getFixedCommissionType();
                                log.info("ItemMethon渠道下的商品   fixedCommissionType=" + fixedCommissionType);
                            }
                        }
                    }

                    if (item.getMerchant_type() == 3) {
                        bean.setSaleType("Q");
                    }
                    bean.setItemType("P");
                    bean.setItemId(item.getGoods_id().toString());
                    bean.setItemTitle(item.getGoods_name());
                    bean.setItemShortTitle(item.getGoods_name());
                    bean.setShopName(item.getMall_name());
                    bean.setHasCoupon(item.getHas_coupon());
                    bean.setCouponMoney(item.getCoupon_discount() == null ? 0 : item.getCoupon_discount().intValue() / 100);
//                    bean.setItemPrice((new BigDecimal(item.getMin_normal_price()).divide(new BigDecimal("100"))).toString());
                    bean.setItemPrice((new BigDecimal(item.getMin_group_price()).divide(new BigDecimal("100"))).toString());
                    bean.setItempictUrl(item.getGoods_image_url());
                    if (item.getGoods_gallery_urls() != null) {
                        bean.setItemSmallImages(item.getGoods_gallery_urls().toString().replace("[", "").
                                replace("]", "").replace(" ", ""));
                        if (bean.getItemSmallImages() != null && bean.getItemSmallImages().split(",").length > 0) {
                            bean.setItemSmallImagesFirst(bean.getItemSmallImages().split(",")[0]);
                        }
                    }
                    if (item.getSales_tip() != null && item.getSales_tip().contains("万")) {
                        String[] strs = item.getSales_tip().split("万");
                        Double sales = Double.parseDouble(strs[0]) * 10000;
                        bean.setItemSale(String.valueOf(sales.intValue()));
                    } else if (item.getSales_tip().contains("+")) {
                        bean.setItemSale(item.getSales_tip().replace("+", ""));
                    } else {
                        bean.setItemSale(item.getSales_tip());
                    }
                    bean.setCouponnum(item.getCoupon_total_quantity().toString());
                    bean.setCouponStartTime(item.getCoupon_start_time().toString());
                    bean.setCouponEndTime(item.getCoupon_end_time().toString());
                    String promotionRate = item.getPromotion_rate() == null ? "0" : item.getPromotion_rate() + "0";

                    //普通分佣
                    AppGeneralFeeScheme generalFeeScheme = appCompany.getPddScheme();
                    BigDecimal itemendprice = BigDecimalUtils.Format(
                            new BigDecimal(bean.getItemPrice() == null ? "0" : bean.getItemPrice())
                                    .subtract(new BigDecimal(bean.getCouponMoney()))
                    );
                    Integer s = getCommissionRate(appCompany, orderFeeScheme, generalFeeScheme, userId == null ? 0 : userId,
                            BigDecimalUtils.TaoBaoCommissionSumScale(promotionRate,
                                    String.valueOf(itemendprice)).doubleValue());

                    if (fixedCommissionType == null) {
                        BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(),
                                BigDecimalUtils.TaoBaoCommissionSumScale(promotionRate,
                                        String.valueOf(itemendprice)));
                        bean.setFanliMoney(fl);
                        bean.setFanlihoMoney(itemendprice);
                        bean.setTheirPriceMoney(itemendprice.subtract(fl));

                    } else {
                        BigDecimal flh = BigDecimalUtils.Format(itemendprice);
                        bean.setFanliMoney(new BigDecimal(fixedCommissionType));
                        bean.setFanlihoMoney(flh);
                        bean.setTheirPriceMoney(flh.subtract(new BigDecimal(fixedCommissionType)));
                    }
                    beans.add(bean);
                }
                results.setData(beans);
                return results;
            }

        } else {
            //普通分佣
            AppGeneralFeeScheme generalFeeScheme = appCompany.getGeneralFeeScheme();
            ServerResponse<List<TbkScMaterialOptionalInfo.MapData>> response =
                    taoBaoService.SearchSuperTitle(keyword, sort, pageSize, pageNo, userId, hasCoupon);
            if (response.getData() != null) {
                ResponeResults results = new ResponeResults();
                List<ResponeResults.DataBean> beans = new ArrayList<ResponeResults.DataBean>();
                for (TbkScMaterialOptionalInfo.MapData item : response.getData()) {
                    ResponeResults.DataBean bean = new ResponeResults.DataBean();
                    String fixedCommissionType = null;
                    if (syChannelGoodsAll != null) {
                        for (SyChannelGoods syChannelGoods : syChannelGoodsAll) {
                            if (syChannelGoods.getItemId().toString().equals(item.getItemId())) {
                                fixedCommissionType = syChannelGoods.getFixedCommissionType();
                                log.info("ItemMethon渠道下的商品   fixedCommissionType=" + fixedCommissionType);
                            }
                        }
                    }
                    bean.setItemId(item.getItemId());
                    bean.setItemTitle(item.getTitle());
                    bean.setItemShortTitle(item.getShortTitle());
                    bean.setItemPrice(item.getZkFinalPrice());
                    bean.setItempictUrl(item.getPictUrl());
                    if (bean.getItempictUrl() != null) {
//                    bean.setItempictUrl(bean.getItempictUrl().replaceAll(".jpg", ".jpg_200x200.jpg"));
                    }
                    bean.setItemType(item.getUserType() == 1 ? "B" : "C");
                    //获取商品图片列表
                    if (item.getSmallImages() == null ||
                            item.getSmallImages().size() < 0) {
                        bean.setItemSmallImages(item.getPictUrl());
//                    bean.setItemSmallImagesFirst(item.getPictUrl().replaceAll(".jpg", ".jpg_200x200.jpg"));
                        bean.setItemSmallImagesFirst(item.getPictUrl());
                    } else {

                        bean.setItemSmallImages(item.getSmallImages().toString().replace("[", "").
                                replace("]", "").replace(" ", ""));
                        if (bean.getItemSmallImages() != null && bean.getItemSmallImages().split(",").length > 0) {
//                        bean.setItemSmallImagesFirst(bean.getItemSmallImages().split(",")[0].replaceAll(".jpg", ".jpg_200x200.jpg"));
                            bean.setItemSmallImagesFirst(bean.getItemSmallImages().split(",")[0]);
                        }
                    }
                    bean.setItemSale(item.getVolume().toString());
                    String coupon = RegUtils.getreGex(item.getCouponInfo() == null ? "减0元" : item.getCouponInfo(), "(?<=减)[0-9]*(?=元)");
                    coupon = coupon == null ? "0" : coupon;
                    bean.setCouponMoney(NumberUtils.toInt(coupon));
                    bean.setCouponStartTime(item.getCouponStartTime() == null ? String.valueOf(System.currentTimeMillis()) : DateFormatUtils.dateToStamp(item.getCouponStartTime()));
                    bean.setCouponEndTime(item.getCouponEndTime() == null ? String.valueOf(System.currentTimeMillis() + 86400000) : DateFormatUtils.dateToStamp(item.getCouponEndTime()));
                    bean.setFreeShipment(true);
                    bean.setHasCoupon(coupon == null ? false : true);
                    bean.setShopId(String.valueOf(item.getSellerId()));
                    bean.setShopName(item.getNick());

                    Integer s = ApiEnum.YOUKEMODE;//游客模式的佣金
                    BigDecimal itemendprice = BigDecimalUtils.Format(
                            new BigDecimal(item.getZkFinalPrice() == null ? "0" : item.getZkFinalPrice())
                                    .subtract(new BigDecimal(coupon))
                    );
                    s = getCommissionRate(appCompany, orderFeeScheme, generalFeeScheme, userId == null ? 0 : userId,
                            BigDecimalUtils.TaoBaoCommissionSum(item.getCommissionRate(),
                                    String.valueOf(itemendprice)).doubleValue());

                    if (fixedCommissionType == null) {
                        BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(),
                                BigDecimalUtils.TaoBaoCommissionSumScale(item.getCommissionRate(),
                                        String.valueOf(itemendprice)));
                        bean.setFanliMoney(fl);
                        bean.setFanlihoMoney(itemendprice);
                        bean.setTheirPriceMoney(itemendprice.subtract(fl));

                    } else {
                        BigDecimal flh = BigDecimalUtils.Format(itemendprice);
                        bean.setFanliMoney(new BigDecimal(fixedCommissionType));
                        bean.setFanlihoMoney(flh);
                        bean.setTheirPriceMoney(flh.subtract(new BigDecimal(fixedCommissionType)));
                    }
                    beans.add(bean);
                }
                results.setData(beans);
                return results;
            } else {
                return null;
            }
        }
        return null;
    }


    /**
     * 首页返回数据
     *
     * @param type
     * @param start
     * @param back
     * @param cid
     * @param recommend
     * @param sort
     * @param userId
     * @param free
     * @param companyId
     * @return
     */
    @Override
    public ResponeResults ItemMethon5(Integer type, Integer start, Integer back, Integer cid, Integer recommend,
                                      Integer sort, Long userId, Boolean free, Integer companyId) {
        // TODO Auto-generated method ItemMethon5
        start = start == null ? 0 : start;
        back = back == null ? 20 : back;
        companyId = companyId == null ? 0 : companyId;
        List<AppGoods> goods = null;
        long startTime = System.currentTimeMillis();
        log.info("ItemMethon5统计时间start" + startTime);
        AppUser user = appUserService.selectAppUserByUserId(userId, 1);
        AppCompany appCompany = appCompanyService.findtAppCompany(user == null ? null : user.getCompanyId(), 1);
        log.info("ItemMethon5统计时间user=" + System.currentTimeMillis() + "------" + (System.currentTimeMillis() - startTime));
        //杀熟分佣
        AppOrderFeeScheme orderFeeScheme = appCompany.getOrderFeeScheme();
        //普通分佣
        AppGeneralFeeScheme generalFeeScheme = appCompany.getGeneralFeeScheme();

        log.info("ItemMethon5统计时间generalFeeScheme=" + System.currentTimeMillis() + "------" + (System.currentTimeMillis() - startTime));
        companyId = -1;
        if (free == false) {//false代表不查免单
            goods = appGoodsService.selectAppGoodsListsNotFree(type, start, back, cid, recommend, sort, companyId);
        } else {
            goods = appGoodsService.selectAppGoodsListsINFree(type, start, back, cid, sort, companyId);
        }
        log.info("ItemMethon5统计时间goods=" + System.currentTimeMillis() + "------" + (System.currentTimeMillis() - startTime));
        ResponeResults results = new ResponeResults();
        List<ResponeResults.DataBean> beans = new ArrayList<>();
        for (AppGoods dataBean : goods) {

            ResponeResults.DataBean bean = new ResponeResults.DataBean();
            bean.setItemId(dataBean.getItemid());
            bean.setItemTitle(dataBean.getItemtitle());
            bean.setItemShortTitle(dataBean.getItemshorttitle());
            bean.setItemPrice(dataBean.getItemprice());
            bean.setItempictUrl(dataBean.getItempic());
            if (bean.getItempictUrl() != null) {
//                bean.setItempictUrl(bean.getItempictUrl().replaceAll(".jpg", ".jpg_200x200.jpg"));
            }
            bean.setItemSmallImages(dataBean.getTaobaoImage() == null ? dataBean.getTaobaoImage() : dataBean.getTaobaoImage().replace(" ", ""));
            if (bean.getItemSmallImages() != null && bean.getItemSmallImages().split(",").length > 0) {
//                bean.setItemSmallImagesFirst(bean.getItemSmallImages().split(",")[0].replaceAll(".jpg", ".jpg_200x200.jpg"));
                bean.setItemSmallImagesFirst(bean.getItemSmallImages().split(",")[0]);
//				bean.setItemSmallImages(bean.getItemSmallImages().replaceAll(".jpg",".jpg_400x400q90.jpg"));
            }
            bean.setCouponUrl(dataBean.getCouponurl());
            bean.setCouponStartTime(dataBean.getCouponstarttime());
            bean.setCouponEndTime(dataBean.getCouponendtime());
            bean.setFreeShipment(true);
            bean.setItemType(dataBean.getShoptype());
            bean.setItemSale(String.valueOf(dataBean.getItemsale()));
            bean.setCouponMoney(BigDecimalUtils.Format(dataBean.getCouponmoney()).intValue());
            bean.setHasCoupon(bean.getCouponMoney() == null ? false : true);
            bean.setShopName(dataBean.getShopname());
            bean.setShopId(dataBean.getShopid());
            WeiYiInfo info = JsonUtils.getJsonToBean(dataBean.getWyItemDetail(), WeiYiInfo.class);
            if (info != null) {
                bean.setShopPicUrl(info.getData().getSeller().getShopIcon() == null ? "" : "https" + info.getData().getSeller().getShopIcon());
                bean.setShopTag(info.getData().getSeller().getTagIcon());
                bean.setShopUrl(info.getData().getSeller().getTaoShopUrl() == null ? "" : "https" + info.getData().getSeller().getTaoShopUrl());
                bean.setItemDetail(info.getData().getItem_detail());
                bean.setEval(info.getData().getSeller().getEvaluates());
            }
            Integer s = ApiEnum.YOUKEMODE;//游客模式的佣金
            s = getCommissionRate(appCompany, orderFeeScheme, generalFeeScheme, ((userId == null) ? 0 : userId), Double.valueOf(dataBean.getTkmoney() == null ? "0" : dataBean.getTkmoney()));
            if (free == false) {
                BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(), BigDecimalUtils.Format(dataBean.getTkmoney() == null ? "0" : dataBean.getTkmoney()));
                BigDecimal flh = BigDecimalUtils.Format(dataBean.getItemendprice());
                bean.setFanliMoney(fl);
                bean.setFanlihoMoney(flh);
                bean.setTheirPriceMoney(flh.subtract(fl));

            } else {//查询免单商品
                GoodsFree free1 = goodsFreeMapper.selectByGoodsId(dataBean.getItemid());
                if (free1 != null) {
                    BigDecimal fl = BigDecimalUtils.Format(dataBean.getTkmoney());
                    BigDecimal flh = BigDecimal.valueOf(0);
                    bean.setFanliMoney(fl);
                    bean.setFanlihoMoney(flh);
                    bean.setTheirPriceMoney(flh.subtract(fl));
                } else {
                    BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(), BigDecimalUtils.Format(dataBean.getTkmoney()));
                    BigDecimal flh = BigDecimalUtils.Format(dataBean.getItemendprice());
                    bean.setFanliMoney(fl);
                    bean.setFanlihoMoney(flh);
                    bean.setTheirPriceMoney(flh.subtract(fl));
                }
            }
            beans.add(bean);
        }
        results.setData(beans);
        return results;
    }

    /**
     * 官方的单品详情
     *
     * @param data
     * @param userId
     * @param channelUserId
     * @return
     */
    @Override
    public ResponeResults ItemMethon6(List<NTbkItem> data, Long userId, String channelUserId, Integer isCollect) {
        // TODO Auto-generated method stub
        ResponeResults results = new ResponeResults();
        List<ResponeResults.DataBean> beans = new ArrayList<>();
        ResponeResults.DataBean bean = new ResponeResults.DataBean();

        AppUser user = appUserService.selectAppUserByUserId(userId, 1);
        AppCompany appCompany = appCompanyService.findtAppCompany(user == null ? null : user.getCompanyId(), 1);

        List<SyChannelGoods> syChannelGoodsAll = syChannelGoodsService.getAllAppChannelGoods(1);
        //杀熟分佣
        AppOrderFeeScheme orderFeeScheme = appCompany.getOrderFeeScheme();
        //普通分佣
        AppGeneralFeeScheme generalFeeScheme = appCompany.getGeneralFeeScheme();

        for (NTbkItem item : data) {
            String fixedCommissionType = null;
            //调用的是高佣的接口实时转链计算的佣金
            ServerResponse<TbkPrivilege> response2 = taoBaoService.getPrivilegeItemId(Long.valueOf(item.getNumIid()), userId, null);
            if (response2 != null && response2.isSuccess()) {
                bean.setItemId(item.getNumIid().toString());
                bean.setItempictUrl(item.getPictUrl());
                if (bean.getItempictUrl() != null) {
//                    bean.setItempictUrl(bean.getItempictUrl().replaceAll(".jpg", ".jpg_200x200.jpg"));
                }
                bean.setItemPrice(item.getZkFinalPrice());
                bean.setItemTitle(item.getTitle());
                bean.setItemShortTitle(item.getTitle());
                bean.setItemType(item.getUserType() == 1 ? "B" : "C");
                if (item.getSmallImages() == null || //获取商品图片列表
                        item.getSmallImages().size() < 0) {
                    bean.setItemSmallImages(item.getPictUrl());
                } else {
                    bean.setItemSmallImages(item.getSmallImages().toString().replace("[", "").
                            replace("]", "").replace(" ", ""));
                }
                if (bean.getItemSmallImages() != null && bean.getItemSmallImages().split(",").length > 0) {
//                    bean.setItemSmallImagesFirst(bean.getItemSmallImages().split(",")[0].replaceAll(".jpg", ".jpg_200x200.jpg"));
                    bean.setItemSmallImagesFirst(bean.getItemSmallImages().split(",")[0]);
//				bean.setItemSmallImages(bean.getItemSmallImages().replaceAll(".jpg",".jpg_400x400q90.jpg"));
                }
                bean.setItemSale(item.getVolume().toString());
                Integer coupon = response2.getData().getCouponInfo() == null ? 0 : NumberUtils.toInt(response2.getData().getCouponInfo());
                bean.setCouponUrl(coupon == 0 ? response2.getData().getItemUrl() : response2.getData().getCouponClickUrl());
                bean.setCouponMoney(coupon);
                bean.setCouponStartTime(coupon == 0 ?
                        String.valueOf(System.currentTimeMillis()) : DateFormatUtils.dateToStamp(response2.getData().getCouponStartTime()));
                bean.setCouponEndTime(coupon == 0 ?
                        String.valueOf(System.currentTimeMillis() + 86400000) : DateFormatUtils.dateToStamp(response2.getData().getCouponEndTime()));
                bean.setFreeShipment(true);
                bean.setHasCoupon(coupon == null ? false : true);
                bean.setShopName(item.getNick());

                //佣金和返后价计算规则
                //券后价  = 原价 - 优惠券金额
                //返利金额 = 券后价 * 佣金比例（佣金比例是%要除100）
                //返后价 = 原价 - 返利金额

                //获取高佣商品固定返
                fixedCommissionType = getFixedCommission(item.getNumIid().toString(), userId, fixedCommissionType, syChannelGoodsAll);

                Integer s = ApiEnum.YOUKEMODE;//游客模式的佣金
                BigDecimal itemendprice = BigDecimalUtils.Format(
                        new BigDecimal(item.getZkFinalPrice() == null ? "0" : item.getZkFinalPrice())
                                .subtract(new BigDecimal(coupon))
                );
                s = getCommissionRate(appCompany, orderFeeScheme, generalFeeScheme, userId, Double.valueOf(
                        BigDecimalUtils.FanliMoney(response2.getData().getMaxCommissionRate(),
                                itemendprice).doubleValue()));

                BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(),
                        BigDecimalUtils.FanliMoney(response2.getData().getMaxCommissionRate(),
                                itemendprice));
                bean.setFanliMoney(fl);
                bean.setFanlihoMoney(itemendprice);
                bean.setTheirPriceMoney(itemendprice.subtract(fl));
            } else {
                if (response2.getStatus() == 601) {
                    results.setMin_id(601);
                    return results;
                }
                return null;
            }

            beans.add(bean);
        }
        results.setData(beans);
        return results;
    }

    /**
     * 本地库单品详情
     *
     * @param appGoods
     * @param userId
     * @param channelUserId
     * @param period
     * @return
     */
    @Override
    public ResponeResults ItemMethon7(AppGoods appGoods, Long userId, String channelUserId, String period, Integer isCollect) {

        AppUser user = appUserService.selectAppUserByUserId(userId, 1);
        AppCompany appCompany = appCompanyService.findtAppCompany(user == null ? null : user.getCompanyId(), 1);

        //杀熟分佣
        AppOrderFeeScheme orderFeeScheme = appCompany.getOrderFeeScheme();
        //普通分佣
        AppGeneralFeeScheme generalFeeScheme = appCompany.getGeneralFeeScheme();
        String fixedCommissionType = null;
        List<SyChannelGoods> syChannelGoodsAll = syChannelGoodsService.getAllAppChannelGoods(1);
        //获取高佣商品固定返
        fixedCommissionType = getFixedCommission(appGoods.getItemid(), userId, fixedCommissionType, syChannelGoodsAll);
        // TODO Auto-generated method stub
        ResponeResults results = new ResponeResults();
        List<ResponeResults.DataBean> beans = new ArrayList<ResponeResults.DataBean>();
        ResponeResults.DataBean bean = new ResponeResults.DataBean();
        //调用的是高佣的接口实时转链计算的佣金
        ServerResponse<TbkPrivilege> response2 = taoBaoService.getPrivilegeItemId(Long.valueOf(appGoods.getItemid()), userId, null);
        if (response2 != null && response2.isSuccess()) {
            if (appGoods.getVideoid() == null || appGoods.getVideoid().isEmpty()) {
                bean.setVideoid("0");
            } else {
                bean.setVideoid(appGoods.getVideoid());
            }
            bean.setActivityId(appGoods.getActivityid());
            //设置是否是秒杀
            bean.setPeriod(period);
            bean.setItemId(appGoods.getItemid());
            bean.setItemTitle(appGoods.getItemtitle());
            bean.setItemShortTitle(appGoods.getItemshorttitle());
            bean.setItemPrice(String.valueOf(appGoods.getItemprice()));
            bean.setItempictUrl(appGoods.getItempic());
            if (bean.getItempictUrl() != null) {
//                bean.setItempictUrl(bean.getItempictUrl().replaceAll(".jpg", ".jpg_200x200.jpg"));
            }
            bean.setItemSmallImages(appGoods.getTaobaoImage() == null ? appGoods.getItempic() : appGoods.getTaobaoImage().replace(" ", ""));
//			bean.setItemSmallImagesFirst(bean.getItemSmallImages() ==null ? bean.getItempictUrl() : bean.getItemSmallImages().split(",")[0].replaceAll(".jpg",".jpg_200x200.jpg"));
            if (bean.getItemSmallImages() != null && bean.getItemSmallImages().split(",").length > 0) {
//                bean.setItemSmallImagesFirst(bean.getItemSmallImages().split(",")[0].replaceAll(".jpg", ".jpg_200x200.jpg"));
//				bean.setItemSmallImages(bean.getItemSmallImages().replaceAll(".jpg",".jpg_400x400q90.jpg"));
                bean.setItemSmallImagesFirst(bean.getItemSmallImages().split(",")[0]);
            }

            Integer coupon = response2.getData().getCouponInfo() == null ? 0 : NumberUtils.toInt(response2.getData().getCouponInfo());
            if (appGoods.getActivityid() != null) {

                bean.setCouponUrl(response2.getData().getCouponClickUrl() + "&activityId=" + appGoods.getActivityid());
//				bean.setCouponStartTime(DateFormatUtils.dateToStamp(response2.getData().getCouponStartTime()));
//				bean.setCouponEndTime(DateFormatUtils.dateToStamp(response2.getData().getCouponEndTime()));
//				bean.setCouponMoney(coupon);
                bean.setCouponStartTime(appGoods.getCouponstarttime());
                bean.setCouponEndTime(appGoods.getCouponendtime());
                bean.setCouponMoney(new Double(appGoods.getCouponmoney()).intValue());
                bean.setHasCoupon(true);
            } else {
                bean.setCouponUrl(response2.getData().getItemUrl());
                bean.setCouponStartTime(String.valueOf(System.currentTimeMillis()));
                bean.setCouponEndTime(String.valueOf(System.currentTimeMillis() + 86400000));
                bean.setCouponMoney(coupon);
                bean.setHasCoupon(false);
            }
            bean.setFreeShipment(true);
            bean.setItemType(appGoods.getShoptype());
            bean.setItemSale(String.valueOf(appGoods.getItemsale()));
            bean.setShopId(appGoods.getShopid());
            bean.setShopName(appGoods.getShopname());
            AppGoodsShopdrs shopdrs = appGoodsShopdrsService.selectAppGoodsShopdrsByShopId(appGoods.getShopid());
            if (shopdrs != null) {
                WeiYiInfo info2 = JsonUtils.getJsonToBean(shopdrs.getWyItemDetail(), WeiYiInfo.class);
                if (info2 != null) {
                    bean.setShopPicUrl(info2.getData().getSeller().getShopIcon() == null ? "" : "https:" + info2.getData().getSeller().getShopIcon());
                    bean.setShopTag(info2.getData().getSeller().getTagIcon());
                    bean.setShopUrl(info2.getData().getSeller().getTaoShopUrl() == null ? "" : "https:" + info2.getData().getSeller().getTaoShopUrl());
                    bean.setItemDetail(info2.getData().getItem_detail());
                    bean.setEval(info2.getData().getSeller().getEvaluates());
                }
            } else {
//			WeiYiInfo info3 = taoBaoService.getShopMessage(appGoods.getItemid(), appGoods.getShoptype());
//			if(info3 != null && RegUtils.getreGex(info3.getMsg(), "成功") != null) {
//				bean.setShopPicUrl(info3.getData().getSeller().getShopIcon() == null?"":"https:"+info3.getData().getSeller().getShopIcon());
//				bean.setShopTag(info3.getData().getSeller().getTagIcon());
//				bean.setShopUrl(info3.getData().getSeller().getTaoShopUrl() == null?"":"https:"+info3.getData().getSeller().getTaoShopUrl());
//				bean.setItemDetail(info3.getData().getItem_detail());
//				bean.setEval(info3.getData().getSeller().getEvaluates());
//			}else {
                bean.setShopPicUrl(null);
                bean.setShopTag(null);
                bean.setShopUrl(null);
                bean.setItemDetail(null);
                bean.setEval(null);
//			}
            }
            Integer s = ApiEnum.YOUKEMODE;//游客模式
            s = getCommissionRate(appCompany, orderFeeScheme, generalFeeScheme, userId, Double.valueOf(appGoods.getTkmoney()));
            if ("1".equals(period)) {
                BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(), BigDecimalUtils.Format(appGoods.getTkmoney()));
                BigDecimal flh = BigDecimalUtils.Format(Double.valueOf(appGoods.getItemendprice()));
                bean.setFanliMoney(fl);
                bean.setFanlihoMoney(flh);
                bean.setTheirPriceMoney(flh.subtract(fl));
            } else {
                //查询免单商品
                GoodsFree free = goodsFreeMapper.selectByGoodsId(appGoods.getItemid());
                if (free != null) {
                    BigDecimal fl = BigDecimalUtils.Format(appGoods.getTkmoney());
                    BigDecimal flh = BigDecimal.valueOf(0);
                    bean.setFanliMoney(fl);
                    bean.setFanlihoMoney(flh);
                    bean.setTheirPriceMoney(flh.subtract(fl));
                } else {
                    if (fixedCommissionType == null) {
                        BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(), BigDecimalUtils.Format(appGoods.getTkmoney()));
                        BigDecimal flh = BigDecimalUtils.Format(Double.valueOf(appGoods.getItemendprice()));
                        bean.setFanliMoney(fl);
                        bean.setFanlihoMoney(flh);
                        bean.setTheirPriceMoney(flh.subtract(fl));
                    } else {
                        if (isCollect != null && isCollect == 1) {
                            BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(), BigDecimalUtils.Format(appGoods.getTkmoney()));
                            BigDecimal flh = BigDecimalUtils.Format(Double.valueOf(appGoods.getItemendprice()));
                            bean.setFanliMoney(fl);
                            bean.setFanlihoMoney(flh);
                            bean.setTheirPriceMoney(flh.subtract(fl));
                        } else {
                            BigDecimal flh = BigDecimalUtils.Format(Double.valueOf(appGoods.getItemendprice()));
                            bean.setFanliMoney(new BigDecimal(fixedCommissionType));
                            bean.setFanlihoMoney(flh);
                            bean.setTheirPriceMoney(flh.subtract(new BigDecimal(fixedCommissionType)));
                        }

                    }
                }
            }

            bean.setActivityType(appGoods.getActivityType());
            bean.setStartTime(appGoods.getStartTime());
            bean.setEndTime(appGoods.getEndTime());
            beans.add(bean);
            results.setData(beans);
            return results;
        } else {
            if (response2.getStatus() == 601) {
                results.setMin_id(601);
                return results;
            }
            return null;
        }
    }

    /**
     * 获取免单商品
     *
     * @param type
     * @param cid
     * @param pageNum
     * @param pageSize
     * @param userId
     * @param companyId
     * @return
     */
    @Override
    public ResponeResults ItemMethon8(
            Integer type, Integer cid, Integer pageNum, Integer pageSize, Long userId, Integer companyId) {
        // TODO Auto-generated method stub
        pageNum = pageNum == null ? 0 : pageNum;
        pageSize = pageSize == null ? 20 : pageSize;
        cid = cid == null ? 0 : cid;
        companyId = companyId == null ? 0 : companyId;
        List<AppGoods> goods = appGoodsService.selectAppGoodsFreeList(
                type, cid, pageNum, pageSize, userId, companyId);

        AppUser user = appUserService.selectAppUserByUserId(userId, 1);
        AppCompany appCompany = appCompanyService.findtAppCompany(user == null ? null : user.getCompanyId(), 1);

        //杀熟分佣
        AppOrderFeeScheme orderFeeScheme = appCompany.getOrderFeeScheme();
        //普通分佣
        AppGeneralFeeScheme generalFeeScheme = appCompany.getGeneralFeeScheme();

        ResponeResults results = new ResponeResults();
        List<ResponeResults.DataBean> beans = new ArrayList<ResponeResults.DataBean>();
        for (AppGoods dataBean : goods) {
            ResponeResults.DataBean bean = new ResponeResults.DataBean();
            bean.setItemId(dataBean.getItemid());
            bean.setItemTitle(dataBean.getItemtitle());
            bean.setItemShortTitle(dataBean.getItemshorttitle());
            bean.setItemPrice(dataBean.getItemprice());
            bean.setItempictUrl(dataBean.getItempic());
            if (bean.getItempictUrl() != null) {
//                bean.setItempictUrl(bean.getItempictUrl().replaceAll(".jpg", ".jpg_200x200.jpg"));
            }
            bean.setItemSmallImages(dataBean.getTaobaoImage() == null ? dataBean.getTaobaoImage() : dataBean.getTaobaoImage().replace(" ", ""));
            bean.setCouponUrl(dataBean.getCouponurl());
            bean.setCouponStartTime(dataBean.getCouponstarttime());
            bean.setCouponEndTime(dataBean.getCouponendtime());
            bean.setFreeShipment(true);
            bean.setItemType(dataBean.getShoptype());
            bean.setItemSale(String.valueOf(dataBean.getItemsale()));
            bean.setCouponMoney(BigDecimalUtils.Format(dataBean.getCouponmoney()).intValue());
            bean.setHasCoupon(bean.getCouponMoney() == null ? false : true);
            bean.setShopName(dataBean.getShopname());
            bean.setShopId(dataBean.getShopid());
            WeiYiInfo info = JsonUtils.getJsonToBean(dataBean.getWyItemDetail(), WeiYiInfo.class);
            if (info != null) {
                bean.setShopPicUrl(info.getData().getSeller().getShopIcon() == null ? "" : "https" + info.getData().getSeller().getShopIcon());
                bean.setShopTag(info.getData().getSeller().getTagIcon());
                bean.setShopUrl(info.getData().getSeller().getTaoShopUrl() == null ? "" : "https" + info.getData().getSeller().getTaoShopUrl());
                bean.setItemDetail(info.getData().getItem_detail());
                bean.setEval(info.getData().getSeller().getEvaluates());
            }

            Integer s = ApiEnum.YOUKEMODE;//游客模式的佣金
            s = getCommissionRate(appCompany, orderFeeScheme, generalFeeScheme, userId,
                    Double.valueOf(dataBean.getTkmoney()));
//            s = userCashschemeService.getCommissionRate(userId, Double.valueOf(dataBean.getTkmoney()));
            BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(), BigDecimalUtils.Format(dataBean.getTkmoney()));
            BigDecimal flh = BigDecimalUtils.Format(dataBean.getItemendprice());
            bean.setFanliMoney(fl);
            bean.setFanlihoMoney(flh);
            bean.setTheirPriceMoney(flh.subtract(fl));
            beans.add(bean);
        }
        results.setData(beans);
        return results;
    }

    /**
     * 猜你喜欢返回结果
     *
     * @param itemId
     * @param deviceValue
     * @param deviceEncrypt
     * @param deviceType
     * @param pageSize
     * @param pageNo
     * @param userId
     * @return
     */
    @Override
    public ResponeResults OptimusMaterial(
            Long itemId, String deviceValue, String deviceEncrypt, String deviceType, Long pageSize, Long pageNo,
            Long userId) {
        // TODO Auto-generated method OptimusMaterial
        List<MapData>
                datas = taoBaoService.getSimilarInfo2(itemId, deviceValue, deviceEncrypt, deviceType, pageSize, pageNo);
        if (datas != null && datas.size() > 0) {

            AppUser user = appUserService.selectAppUserByUserId(userId, 1);
            AppCompany appCompany = appCompanyService.findtAppCompany(user == null ? null : user.getCompanyId(), 1);

            //杀熟分佣
            AppOrderFeeScheme orderFeeScheme = appCompany.getOrderFeeScheme();
            //普通分佣
            AppGeneralFeeScheme generalFeeScheme = appCompany.getGeneralFeeScheme();

            ResponeResults results = new ResponeResults();
            List<ResponeResults.DataBean> beans = new ArrayList<ResponeResults.DataBean>();
            for (MapData item : datas) {
                //调用的是高佣的接口实时转链计算的佣金
                ServerResponse<TbkPrivilege> response2 = taoBaoService.getPrivilegeItemId(itemId, userId, null);

                ResponeResults.DataBean bean = new ResponeResults.DataBean();
                bean.setItemId(item.getItemId().toString());
                bean.setItemTitle(item.getTitle());
                bean.setItemShortTitle(item.getShortTitle());
                bean.setItemPrice(item.getZkFinalPrice());
                bean.setItempictUrl("https:" + item.getPictUrl());
                if (bean.getItempictUrl() != null) {
//                    bean.setItempictUrl(bean.getItempictUrl().replaceAll(".jpg", ".jpg_200x200.jpg"));
                }
                bean.setItemType(item.getUserType() == 1 ? "B" : "C");
                if (item.getSmallImages() == null || //获取商品图片列表
                        item.getSmallImages().size() < 0) {
                    bean.setItemSmallImages(item.getPictUrl());
                } else {
                    bean.setItemSmallImages(item.getSmallImages().toString().replace("[", "").
                            replace("]", "").replace("//", "https://").replace(" ", ""));
                }
                bean.setItemSale(item.getVolume().toString());
                bean.setCouponMoney(item.getCouponAmount().intValue());
                bean.setCouponStartTime(item.getCouponStartTime());
                bean.setCouponEndTime(item.getCouponEndTime());
                bean.setFreeShipment(true);
                bean.setHasCoupon(item.getCouponAmount() == null ? false : true);
                bean.setShopName(item.getNick());
                Long amout = item.getCouponAmount() == null ? 0 : item.getCouponAmount();

                if (response2 != null && response2.isSuccess()) {
                    bean.setItemSale(item.getVolume().toString());
                    bean.setCouponUrl(response2.getData().getCouponInfo() == null ? response2.getData().getItemUrl() : response2.getData().getCouponClickUrl());
                    Integer coupon = response2.getData().getCouponInfo() == null ? 0 : NumberUtils.toInt(response2.getData().getCouponInfo());
                    bean.setCouponMoney(coupon);
                    String couponStartTime = response2.getData().getCouponStartTime();
                    String couponEndTime = response2.getData().getCouponEndTime();

                    bean.setCouponStartTime(couponStartTime == null ? String.valueOf(System.currentTimeMillis()) : DateFormatUtils.dateToStamp(couponStartTime));
                    bean.setCouponEndTime(couponEndTime == null ? String.valueOf(System.currentTimeMillis() + 86400000) : DateFormatUtils.dateToStamp(couponEndTime));
//                        bean.setCouponEndTime(couponEndTime);
//                        bean.setCouponStartTime(couponStartTime);
                    bean.setFreeShipment(true);
                    bean.setHasCoupon(response2.getData().getCouponInfo() == null ? false : true);
                    bean.setShopName(item.getNick());
                    //佣金和返后价计算规则
                    //券后价  = 原价 - 优惠券金额
                    //返利金额 = 券后价 * 佣金比例（佣金比例是%要除100）
                    //返后价 = 原价 - 返利金额
                    //到手价 = 原价 - 返利金额- （新修改）返利金额
                    //节省价格 = 券价+返利
                    Integer s = ApiEnum.YOUKEMODE;//游客模式的佣金
                    BigDecimal itemendprice = BigDecimalUtils.Format(
                            new BigDecimal(item.getZkFinalPrice() == null ? "0" : item.getZkFinalPrice())
                                    .subtract(new BigDecimal(coupon))
                    );
                    s = getCommissionRate(appCompany, orderFeeScheme, generalFeeScheme, userId,
                            BigDecimalUtils.FanliMoney(response2.getData().getMaxCommissionRate(),
                                    itemendprice).doubleValue());

                    BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(),
                            BigDecimalUtils.FanliMoney(response2.getData().getMaxCommissionRate(),
                                    itemendprice));
                    bean.setFanliMoney(fl);
                    bean.setFanlihoMoney(itemendprice);
                    bean.setTheirPriceMoney(itemendprice.subtract(fl));
                    bean.setSpareMoney(fl.add(new BigDecimal(coupon)));

                } else {
                    Integer s = ApiEnum.YOUKEMODE;//游客模式的佣金
                    BigDecimal itemendprice = BigDecimalUtils.Format(
                            new BigDecimal(item.getZkFinalPrice() == null ? "0" : item.getZkFinalPrice())
                                    .subtract(new BigDecimal(amout))
                    );
                    s = getCommissionRate(appCompany, orderFeeScheme, generalFeeScheme, userId,
                            BigDecimalUtils.FanliMoney(response2.getData().getMaxCommissionRate(),
                                    itemendprice).doubleValue());

                    BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(),
                            BigDecimalUtils.FanliMoney(item.getCommissionRate(),
                                    itemendprice));
                    bean.setFanliMoney(fl);
                    bean.setFanlihoMoney(itemendprice);
                    bean.setTheirPriceMoney(itemendprice.subtract(fl));
                }
                beans.add(bean);
            }
            results.setData(beans);
            return results;
        } else {
            return null;
        }
    }


    /**
     * 用户佣金比例计算逻辑
     *
     * @param appCompany
     * @param orderFeeScheme
     * @param generalFeeScheme
     * @param userId
     * @param commission
     * @return
     */
    @Override
    public Integer getCommissionRate(AppCompany appCompany, AppOrderFeeScheme orderFeeScheme, AppGeneralFeeScheme
            generalFeeScheme, Long userId, Double commission) {
        //杀熟分佣
        if (orderFeeScheme != null) {
            int countOrderNum = appUserOrderService.countBingOrderSum(userId);
            if (orderFeeScheme.getOneorderScale() > countOrderNum) {
                return orderFeeScheme.getOneorderScale();
            } else if (orderFeeScheme.getTwoorder() > countOrderNum) {
                return orderFeeScheme.getTwoorderScale();
            } else if (orderFeeScheme.getThirdorder() > countOrderNum) {
                return orderFeeScheme.getThirdorderScale();
            }
        }

        //普通分佣
        if (generalFeeScheme != null) {
            if (generalFeeScheme.getOnepay() >= commission) {
                return generalFeeScheme.getOnepayScale();
            } else if (generalFeeScheme.getTwopay() >= commission) {
                return generalFeeScheme.getTwopayScale();
            } else if (generalFeeScheme.getThirdpay() >= commission) {
                return generalFeeScheme.getThirdpayScale();
            } else if (generalFeeScheme.getForpay() >= commission) {
                return generalFeeScheme.getForpayScale();
            } else if (generalFeeScheme.getFivepay() >= commission) {
                return generalFeeScheme.getFivepayScale();
            } else if (generalFeeScheme.getSixpay() >= commission) {
                return generalFeeScheme.getSixpayScale();
            } else if (generalFeeScheme.getSevenpay() >= commission) {
                return generalFeeScheme.getSevenpayScale();
            } else {
                return generalFeeScheme.getSevenpayScale();
            }
        }
        return 0;
    }


    /**
     * 封转方法
     * 获取我的订单
     *
     * @param userId
     * @param tkStatus
     * @return
     */
    @Override
    public List<OrderDataBean> getMeOrderDetailMethon(Integer tkStatus,
                                                      Integer pageNum, Integer pageSize, Long userId, String orderType, String version) {
        // TODO Auto-generated method getMeOrderDetailMethon
        //userId = Long.parseLong("600526834836");//lyl
        userId = Long.parseLong("601889321269");//77
        List<AppOrderDetailVo> details = null;
//        CommissionFreeze commissionFreeze = commissionFreezeService.selectByPrimaryKey(2, 1);
        if (3 == tkStatus) {//已到账
            details = appOrderDetailService.selectAppOrderDetailTkStatus3(userId, tkStatus, pageNum, pageSize);
        } else if (13 == tkStatus) {//无效订单
            details = appOrderDetailService.selectAppOrderDetailTkStatus13(userId, tkStatus, pageNum, pageSize);
        } else if (12 == tkStatus || 14 == tkStatus) {//入账中
            details = appOrderDetailService.selectAppOrderDetailTkStatusNot3And13(userId, tkStatus, pageNum, pageSize);
        } else if (0000 == tkStatus) {//全部订单
            details = appOrderDetailService.selectAppOrderDetailTkStatusAll(userId, tkStatus, pageNum, pageSize);
        }

        if (details != null && details.size() > 0) {

            List<OrderDataBean> resultsOrder = new ArrayList<>();

            for (AppOrderDetailVo orderDataBean : details) {
                OrderDataBean result = new OrderDataBean();
                result.setItemTitle(orderDataBean.getItemTitle());
                result.setItemPicUrl(orderDataBean.getItemPic());
//                if (result.getItemPicUrl() != null) {
//                    result.setItemPicUrl(result.getItemPicUrl().replaceAll(".jpg", ".jpg_200x200.jpg"));
//                }
                result.setItemPrice(BigDecimalUtils.Format(orderDataBean.getAlipayTotalPrice() == null ? 0 :
                        Double.valueOf(orderDataBean.getAlipayTotalPrice())));
                result.setItemNum(orderDataBean.getItemNum().toString());
                result.setOrderId(orderDataBean.getTradeId().toString());
//                if (StringUtils.isNotNull(version) && "2.4.8".compareTo(version) < 0) {
//                    if (orderDataBean.getOrderType().equals("京东商城")) {
//                        result.setOrderType("J");
//                    } else if (orderDataBean.getOrderType().equals("拼多多")) {
//                        result.setOrderType("P");
//                    } else {
//                        result.setOrderType("C");
//                    }
//                } else {
                result.setOrderType(orderDataBean.getOrderType().contains("天猫") ? "B" : "C");
//                }
                result.setOrderStatus(orderDataBean.getPayStatus());

                //区分订单是否是维权订单，是全维权还是半维权
                boolean wqflag = false;//(1:是维权；0:不是维权)
                String describe = null;//维权订单提示文字
                if (orderDataBean.getMaintainType() > 0) {
                    wqflag = true;
                    //扣除的补贴
                    String commission1 = orderDataBean.getMeCommission();
                    double sub = ComputeUtil.sub(new BigDecimal(orderDataBean.getCommissionOld()).doubleValue(), new BigDecimal(commission1).doubleValue());
                    describe = "部分退款，已扣除" + sub + "元补贴";
                    if (2 == orderDataBean.getMaintainType()) {
                        describe = "已退款，已扣除" + sub + "元补贴";
                    }
                }

                //===============订单状态文字显示处理=================
                //确认收货订单
                String meCommission1 = orderDataBean.getMeCommission();
                double v = new BigDecimal(meCommission1).doubleValue();

                if (orderDataBean.getOrderStatus() == 14) {
                    result.setOrderStatus("14");
                    result.setDescribe("已收货，订单努力结算中~");//入账中
                    if (wqflag) {
                        result.setDescribe(describe);
                    }
                }
                //已结算订单
                if (orderDataBean.getOrderStatus() == 3) {
                    result.setOrderStatus("3");
                    //免单却未结算
                    if (orderDataBean.getGoodFrees() != null && orderDataBean.getGoodFrees() == 1 && "1".equals(orderDataBean.getOrderSettleStatus())) {
                        result.setOrderStatus("21");
                        if (orderDataBean != null && orderDataBean.getFreezeDay() != null) {
                            result.setDescribe("免单商品已收货," + orderDataBean.getFreezeDay() + "天后补贴自动到账");
                        }
                        //入账中
                        result.setOrderSettleTime(orderDataBean.getEarningTime().toString());
                        //大额延迟补贴未到账
                    } else if (orderDataBean.getGoodFrees() != null && orderDataBean.getGoodFrees() == 2 && "1".equals(orderDataBean.getOrderSettleStatus())) {
                        result.setOrderStatus("21");
                        //入账中,已收货，8天后补贴自动到账
                        if (orderDataBean != null && orderDataBean.getFreezeDay() != null) {
                            result.setDescribe("积分商品已收货," + orderDataBean.getFreezeDay() + "天后补贴自动到账");
                        }
                        result.setOrderSettleTime(orderDataBean.getEarningTime().toString());
                    } else if ("1".equals(orderDataBean.getOrderSettleStatus())) {
                        result.setOrderStatus("21");
                        //入账中,已收货，8天后补贴自动到账
                        if (orderDataBean != null && orderDataBean.getFreezeDay() != null) {
                            result.setDescribe("已收货," + orderDataBean.getFreezeDay() + "天后补贴自动到账");
                        }
                        result.setOrderSettleTime(orderDataBean.getEarningTime().toString());
                    } else {
                        //result.setDescribe("已结算");
                        result.setOrderSettleTime(orderDataBean.getEarningTime().toString());
                    }
                    if (wqflag) {
                        result.setDescribe(describe);
                    }
                }
                //已付款订单
                if (orderDataBean.getOrderStatus() == 12) {
                    result.setOrderStatus("12");
                    //是预付款的订单
                    if (StringUtils.isNotNull(orderDataBean.getTkDepositTime())
                            && StringUtils.isNotNull(orderDataBean.getTbDepositTime())
                            && StringUtils.isNotNull(orderDataBean.getDepositPrice())
                            && !"--".equals(orderDataBean.getTkDepositTime())
                            && !"--".equals(orderDataBean.getTbDepositTime())
                            && new BigDecimal(orderDataBean.getDepositPrice()).compareTo(new BigDecimal(0)) > 0
                    ) {
                        //尾款已付
                        if ((new BigDecimal(orderDataBean.getAlipayTotalPrice())).compareTo(new BigDecimal(orderDataBean.getDepositPrice())) > 0) {
                            result.setOrderStatus("22");
                            //入账中
                            result.setDescribe("已付尾款，收货后补贴到账");
                        } else {
                            result.setOrderStatus("21");
                            //入账中
                            result.setDescribe("已付定金,确认收货后补贴到账");
                        }
                    } else {//非预付款订单
                        //入账中
                        result.setDescribe("确认收货后补贴到账");
                    }
                    if (wqflag) {
                        result.setDescribe(describe);
                    }
                }
                //失效订单
                if (orderDataBean.getOrderStatus() == 13  && orderDataBean.getMaintainType()== 2) {
                    result.setOrderStatus("13");
                    //result.setDescribe("订单失效");
//                    if (wqflag) {
//                        result.setDescribe(describe);
//                    }
                }


                result.setOrderCreateTime(orderDataBean.getCreateTime().toString());
                result.setShopName(orderDataBean.getSellerShopTitle());

                String meCommission = orderDataBean.getMeCommission();
                BigDecimal commission = null;
                if (meCommission != null && !"".equals(meCommission)) {
                    commission = new BigDecimal(meCommission);
                }
                result.setFanliMoney(commission);

                resultsOrder.add(result);
            }
            return resultsOrder;
        } else {
            return null;
        }
    }


    /**
     * 取我的收益-入账中订单-包含自己订单，直接粉丝订单，间接粉丝订单，分享赚订单     tkStatus = 12
     *
     * @param tkStatus
     * @param pageNum
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public List<OrderDataBean> getMeBookedOrderDetail(Integer tkStatus,
                                                      Integer pageNum, Integer pageSize, Long userId) {
        // TODO Auto-generated method getMeOrderDetailMethon
//		List<AppOrderDetail> details = null;
        pageNum = pageNum == null ? 0 : pageNum;
        pageSize = pageSize == null ? 20 : pageSize;
        CommissionFreeze commissionFreeze = commissionFreezeService.selectByPrimaryKey(2, 1);
        AppUser user = appUserService.selectAppUserByUserId(userId, 1);

        List<AppUserOrder> appUserOrders = appUserOrderService.getMeBookedOrderDetail(userId, user.getMeInviteCode(), pageNum, pageSize);

//        List<WebCircleFriends> webCircleFriends = iWebCircleFriendsService.selectWebCircleFriendsListAll();
//        Set<String> webCircleFriendItemId = new HashSet<>();
//        if (webCircleFriends != null) {
//            for (WebCircleFriends webCircleFriend : webCircleFriends) {
//                webCircleFriendItemId.add(webCircleFriend.getItemid());
//            }
//        }


        if (appUserOrders != null && appUserOrders.size() > 0) {
            List<OrderDataBean> resultsOrder = new ArrayList<>();
            for (AppUserOrder appUserOrder : appUserOrders) {
                AppOrderDetail orderDataBean = appOrderDetailService.selectAppOrderDetailByTradeId(appUserOrder.getOrderId());

                OrderDataBean result = new OrderDataBean();
                if (orderDataBean != null && orderDataBean.getGoodFrees() != null && orderDataBean.getGoodFrees() == 1) {
                    if (orderDataBean.getTkStatus() == 12) {
                        result.setDescribe("确认收货后补贴到账");
                    } else if (orderDataBean.getTkStatus() == 3) {
                        result.setDescribe("免单商品，补贴冻结8天");
                        result.setOrderSettleTime(orderDataBean.getEarningTime().toString());
                    } else if (orderDataBean.getTkStatus() == 14) {
                        result.setDescribe("已收货，订单努力结算中~");
                    }

                } else {
                    if (orderDataBean.getTkStatus() == 12) {
                        result.setDescribe("确认收货后补贴到账");
                    } else if (orderDataBean.getTkStatus() == 3) {
                        result.setDescribe("已收货，补贴冻结" + commissionFreeze.getDelaydays() + "天");
                        result.setOrderSettleTime(orderDataBean.getEarningTime().toString());
                    } else if (orderDataBean.getTkStatus() == 14) {
                        result.setDescribe("已收货，订单努力结算中~");
                    }
                }
                result.setItemTitle(orderDataBean.getItemTitle());
                result.setItemPicUrl(orderDataBean.getItemPic());
                if (result.getItemPicUrl() != null) {
//                    result.setItemPicUrl(result.getItemPicUrl().replaceAll(".jpg", ".jpg_200x200.jpg"));
                }
                result.setItemPrice(BigDecimalUtils.Format(orderDataBean.getAlipayTotalPrice() == null ? 0 :
                        Double.valueOf(orderDataBean.getAlipayTotalPrice())));
                result.setItemNum(orderDataBean.getItemNum().toString());
                result.setOrderId(orderDataBean.getTradeId().toString());
                result.setOrderType(orderDataBean.getOrderType().equals("天猫") ? "B" : "C");
                result.setOrderStatus(orderDataBean.getPayStatus());
                result.setOrderCreateTime(orderDataBean.getCreateTime().toString());
                result.setShopName(orderDataBean.getSellerShopTitle());

                if (appUserOrder.getOrderGrade() == 1) {
                    result.setType("");
                    result.setOrderStatus("15");
                } else if (appUserOrder.getOrderGrade() == 2) {
                    result.setType("直属粉丝");
                    result.setOrderStatus("16");
                } else if (appUserOrder.getOrderGrade() == 3) {
                    result.setType("间接粉丝");
                    result.setOrderStatus("17");
                } else {
                    result.setType("");
                    result.setOrderStatus("15");
                }

                if (appUserOrder != null && appUserOrder.getOrderStatus() != null
                        && appUserOrder.getOrderStatus() == 3
                        && appUserOrder.getOrderSettleStatus() != null
                        && appUserOrder.getOrderSettleStatus() != 2) {
                    result.setOrderStatus("21");
                }
                if (appUserOrder != null && appUserOrder.getOrderStatus() != null
                        && appUserOrder.getOrderStatus() == 14
                        && appUserOrder.getOrderSettleStatus() != null
                        && appUserOrder.getOrderSettleStatus() != 2) {
                    result.setOrderStatus("21");
                }

                result.setFanliMoney(appUserOrder.getCommission());
//                if (webCircleFriendItemId.contains(orderDataBean.getItemId())) {
//                    result.setBuyFriends("1");
//                    result.setOrderStatus("18");
//                } else {
//                    result.setBuyFriends("0");
////					result.setOrderStatus("15");
//                }


                resultsOrder.add(result);
            }
            return resultsOrder;
        } else {
            return null;
        }
    }

    /**
     * 根据订单编号查询订单信息
     *
     * @param orderId
     * @param userId
     * @return
     */
    @Override
    public List<OrderDataBean> getOrderIdDetailMethon(Long orderId, Long userId) {
        // TODO Auto-generated method getOrderIdDetailMethon
        if (orderId != null && !"".equals(orderId.toString())) {
            List<AppOrderDetail> details = appOrderDetailService.selectAppOrderDetailBytradeId(userId, orderId);
            if (details.size() > 0) {
                List<OrderDataBean> resultsOrder = new ArrayList<>();
                for (AppOrderDetail orderDataBean : details) {
                    OrderDataBean result = new OrderDataBean();
                    result.setItemTitle(orderDataBean.getItemTitle());
                    result.setItemPicUrl(orderDataBean.getItemPic());
                    if (result.getItemPicUrl() != null) {
//                        result.setItemPicUrl(result.getItemPicUrl().replaceAll(".jpg", ".jpg_200x200.jpg"));
                    }
                    result.setItemPrice(BigDecimalUtils.Format(Double.valueOf(orderDataBean.getAlipayTotalPrice() == null ? 0 :
                            Double.valueOf(orderDataBean.getAlipayTotalPrice()))));
                    result.setItemNum(orderDataBean.getItemNum().toString());
                    result.setOrderId(orderDataBean.getTradeId().toString());
                    result.setOrderType(orderDataBean.getOrderType().equals("天猫") ? "B" : "C");
                    result.setOrderStatus(orderDataBean.getPayStatus());
                    result.setOrderCreateTime(orderDataBean.getCreateTime().toString());
                    result.setShopName(orderDataBean.getSellerShopTitle());

                    AppUser user = appUserService.selectAppUserByUserId(userId, 1);
                    if (user != null && user.getEnable() == 0) {//禁用
                        result.setFanliMoney(BigDecimalUtils.Format("0"));
                    } else {
//						Integer s = userCashschemeService.getCommissionRate(userId,
//								BigDecimalUtils.TaoBaoCommissionSum2(orderDataBean.getIncomeRate(), orderDataBean.getAlipayTotalPrice()).doubleValue());
                        AppUserOrder order = appUserOrderService.findUserIdOrderId(userId, orderDataBean.getTradeId());
                        result.setFanliMoney(order.getCommission());
                    }
                    resultsOrder.add(result);
                }
                return resultsOrder;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 我的团队订单
     *
     * @param appUserId
     * @param userId
     * @param details2
     * @param i
     * @return
     */
    @Override
    public List<OrderDataBean> getTeamOrderDetail(Long appUserId, Long userId, List<AppOrderDetail> details2,
                                                  int i) {
        // TODO Auto-generated method stub
        if (details2.size() > 0) {
            List<OrderDataBean> resultsOrder = new ArrayList<>();
            for (AppOrderDetail orderDataBean : details2) {
                OrderDataBean result = new OrderDataBean();
                result.setItemTitle(orderDataBean.getItemTitle());
                result.setItemPicUrl(orderDataBean.getItemPic());
                if (result.getItemPicUrl() != null) {
//                    result.setItemPicUrl(result.getItemPicUrl().replaceAll(".jpg", ".jpg_200x200.jpg"));
                }
                result.setItemPrice(BigDecimalUtils.Format(Double.valueOf(orderDataBean.getAlipayTotalPrice() == null ? 0 :
                        Double.valueOf(orderDataBean.getAlipayTotalPrice()))));
                result.setItemNum(orderDataBean.getItemNum().toString());
                result.setOrderId(orderDataBean.getTradeId().toString());
                result.setOrderType(orderDataBean.getOrderType().equals("天猫") ? "B" : "C");
                result.setOrderStatus(orderDataBean.getPayStatus());
                result.setOrderCreateTime(orderDataBean.getCreateTime().toString());
                result.setShopName(orderDataBean.getSellerShopTitle());
                if (i == 1) {
                    result.setType("直属粉丝");
                } else {
                    result.setType("间接粉丝");
                }

                AppUserOrder order = appUserOrderService.findUserIdOrderId(appUserId, orderDataBean.getTradeId());
                result.setFanliMoney(order == null ? new BigDecimal(0) : order.getCommission());
                resultsOrder.add(result);
            }
            return resultsOrder;
        } else {
            return null;
        }
    }

    @Override
    public String getFixedCommission(String itemId, Long userId, String
            fixedCommissionType, List<SyChannelGoods> syChannelGoodsAll) {
        AppUserOrder appUserOrder = appUserOrderMapper.selectOrderTypeByUser(userId, Long.parseLong(itemId));
        //是否购买过固定返
        if (appUserOrder == null) {
            if (syChannelGoodsAll != null) {
                for (SyChannelGoods syChannelGoods : syChannelGoodsAll) {
                    if (syChannelGoods.getItemId().toString().equals(itemId)) {
                        fixedCommissionType = syChannelGoods.getFixedCommissionType();
                        log.info("ItemMethon渠道下的商品   fixedCommissionType=" + fixedCommissionType);
                        return fixedCommissionType;
                    }
                }
            }
        }
        return null;
    }

    @Override
    public List<OrderDataBean> getJdOrderDetailMethon(Integer tkStatus, Integer pageNum, Integer pageSize, Long userId, String orderType, String version) {
        List<AppOrderDetailVo> details = appOrderDetailService.selectJdOrderDetailTkStatus(userId, tkStatus, pageNum, pageSize);

        if (details != null && details.size() > 0) {
            List<OrderDataBean> resultsOrder = new ArrayList<>();
            for (AppOrderDetailVo orderDataBean : details) {
                OrderDataBean result = new OrderDataBean();
                result.setItemTitle(orderDataBean.getItemTitle());
                result.setItemPicUrl(orderDataBean.getItemPic());
                result.setItemPrice(BigDecimalUtils.Format(orderDataBean.getAlipayTotalPrice() == null ? 0 :
                        Double.valueOf(orderDataBean.getAlipayTotalPrice())));
                result.setItemNum(orderDataBean.getItemNum().toString());
                result.setOrderId(orderDataBean.getOrderId());
                result.setOrderType("J");
//                result.setOrderStatus(orderDataBean.getPayStatus());
                CommissionFreeze commissionFreeze = commissionFreezeService.selectByPrimaryKey(2, 1);
                Integer delaydays = commissionFreeze.getDelaydays();
                orderDataBean.setFreezeDay(delaydays);


                //已结算订单
                if (orderDataBean.getOrderStatus() == 3) {
                    if ("1".equals(orderDataBean.getOrderSettleStatus())) {
                        result.setOrderStatus("21");
                        //入账中,已收货，8天后补贴自动到账
                        if (orderDataBean != null && orderDataBean.getFreezeDay() != null) {
                            result.setDescribe("已收货," + orderDataBean.getFreezeDay() + "天后补贴自动到账");
                        }
                        result.setOrderSettleTime(orderDataBean.getEarningTime().toString());
                    } else {
                        result.setOrderStatus("3");
                        //result.setDescribe("已结算");
                        result.setOrderSettleTime(orderDataBean.getEarningTime().toString());
                    }
                }
                //失效订单
                if (orderDataBean.getOrderStatus() == 13) {
                    result.setOrderStatus("13");
                }
                if (orderDataBean.getOrderStatus() == 12) {
                    result.setOrderStatus("12");
                    result.setDescribe("确认收货后补贴到账");
                }
                result.setOrderCreateTime(orderDataBean.getCreateTime().toString());
                result.setShopName(orderDataBean.getSellerShopTitle());

                String meCommission = orderDataBean.getMeCommission();
                BigDecimal commission = null;
                if (meCommission != null && !"".equals(meCommission)) {
//                    commission = new BigDecimal(meCommission);
                    commission = BigDecimalUtils.Format(Double.valueOf(meCommission));
                }
                result.setFanliMoney(commission);

                resultsOrder.add(result);
            }
            return resultsOrder;
        } else {
            return null;
        }
    }

    @Override
    public List<OrderDataBean> getPddOrderDetailMethon(Integer tkStatus, Integer pageNum, Integer pageSize, Long userId, String orderType, String version) {
        List<AppOrderDetailVo> details = appOrderDetailService.selectPddOrderDetailTkStatus(userId, tkStatus, pageNum, pageSize);
        if (details != null && details.size() > 0) {

            List<OrderDataBean> resultsOrder = new ArrayList<>();

            for (AppOrderDetailVo orderDataBean : details) {
                OrderDataBean result = new OrderDataBean();
                result.setItemTitle(orderDataBean.getItemTitle());
                result.setItemPicUrl(orderDataBean.getItemPic());
                result.setItemPrice(BigDecimalUtils.Format(orderDataBean.getAlipayTotalPrice() == null ? 0 :
                        Double.valueOf(orderDataBean.getAlipayTotalPrice())));
                result.setItemNum(orderDataBean.getItemNum().toString());
                result.setOrderId(orderDataBean.getOrderId());
                result.setOrderType("P");
                orderDataBean.setCreateTime(orderDataBean.getCreateTime() == null ? null : Long.parseLong(orderDataBean.getCreateTime() + "000"));
                orderDataBean.setEarningTime(orderDataBean.getEarningTime() == null ? null : Long.parseLong(orderDataBean.getEarningTime() + "000"));
//                result.setOrderStatus(orderDataBean.getPayStatus());
                CommissionFreeze commissionFreeze = commissionFreezeService.selectByPrimaryKey(2, 1);
                Integer delaydays = commissionFreeze.getDelaydays();
                orderDataBean.setFreezeDay(delaydays);


                //已结算订单
                if (orderDataBean.getOrderStatus() == 3) {
                    if ("1".equals(orderDataBean.getOrderSettleStatus())) {
                        result.setOrderStatus("21");
                        //入账中,已收货，8天后补贴自动到账
                        if (orderDataBean != null && orderDataBean.getFreezeDay() != null) {
                            result.setDescribe("已收货," + orderDataBean.getFreezeDay() + "天后补贴自动到账");
                        }
                        result.setOrderSettleTime(orderDataBean.getEarningTime().toString());
                    } else {
                        result.setOrderStatus("3");
                        result.setOrderSettleTime(orderDataBean.getEarningTime().toString());
                    }
                }
                //失效订单
                if (orderDataBean.getOrderStatus() == 13) {
                    result.setOrderStatus("13");
                }
                if (orderDataBean.getOrderStatus() == 12) {
                    result.setOrderStatus("12");
                    result.setDescribe("确认收货后补贴到账");
                }
                result.setOrderCreateTime(orderDataBean.getCreateTime().toString());
                result.setShopName(orderDataBean.getSellerShopTitle());

                String meCommission = orderDataBean.getMeCommission();
                BigDecimal commission = null;
                if (meCommission != null && !"".equals(meCommission)) {
//                    commission = new BigDecimal(meCommission);
                    commission = BigDecimalUtils.Format(Double.valueOf(meCommission));
                }
                result.setFanliMoney(commission);

                resultsOrder.add(result);
            }
            return resultsOrder;
        } else {
            return null;
        }
    }

    public static long getDateTime(Long earningTime, Integer start) {
        Date paramDate = null;
        if (earningTime == null) {
            paramDate = new Date();
        } else {
            paramDate = new Date(earningTime);
        }
        return org.apache.commons.lang3.time.DateUtils.addDays(paramDate, start).getTime();
    }
}
